私は現在、アンドロイドを使用して古い学校の戦艦ボードゲームに基づいたゲームを作ろうとしています。現時点では、ゲームの作成に必要なコンポーネントの感触を掴もうとしているところです。
基本的に、現時点でレイアウト xml ファイルにあるものは次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<org.greene.battleship.BoardView
android:id="@+id/board_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.greene.battleship.ShipView
android:id="@+id/ships_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
</RelativeLayout>
</RelativeLayout>
BoardView が画面の特定の部分のみを占めるようにしたい。つまり、ビューは、このビューで作成したいコンテンツのサイズである必要があります。この場合は 2D ボードです。これは、View の拡張から onMeasure() メソッドをオーバーライドすることによって行われます。ビューの幅は同じに保たれますが、高さには幅と同じ値が与えられ、完全な正方形が得られます。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parent_width = MeasureSpec.getSize(widthMeasureSpec);
this.setMeasuredDimension(parent_width, parent_width);
Log.d("BOARD_VIEW", "BoardView.onMeasure : width = " + this.getMeasuredWidth() + ", height = "
+ this.getMeasuredHeight());
}
ビューの onSizeChanged() 関数をオーバーライドして値を確認することで、ビューのサイズが変更されたかどうかを確認します。
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
Log.d("BOARD_VIEW", "BoardView.onSizeChanged : width = " + w + ", height = " + h);
board = new Board(w, h, game_activity);
super.onSizeChanged(w, h, oldw, oldh);
}
レイアウト ファイルからわかるように、ShipView という別のカスタム ビューを子として保持する RelativeLayout ビュー グループがあります。そして、理想的には、その寸法を測定するときに、その寸法が onMeasure で設定されたものに限定されていることを望んでいます。同様の方法で onMeasure() メソッドを介して ShipView の寸法を確認します。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parent_width = MeasureSpec.getSize(widthMeasureSpec);
int parent_height = MeasureSpec.getSize(heightMeasureSpec);
Log.d("SHIP_VIEW", "ShipView.onMeasure : width = " + parent_width + ", height = " + parent_height);
this.setMeasuredDimension(parent_width, parent_height);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
ログ ファイルには次のように表示されます (onMeasure() メソッドは複数回呼び出されているようですが、すべての値が同じであるため、値がすべて同じであるため、複数のログを表示する必要はありません)。
05-04 16:36:19.428: DEBUG/BOARD_VIEW(405): BoardView.onMeasure : width = 320, height = 320
05-04 16:36:19.939: DEBUG/BOARD_VIEW(405): BoardView.onSizeChanged : width = 320, height = 320
05-04 16:36:20.429: DEBUG/SHIP_VIEW(405): ShipView.onMeasure : width = 320, height = 430
ShipViews onMeasure() を介して寸法を取得すると、何も変更されておらず、設定した寸法制限が無視されているようです。ShipView の RelativeLayout と関係があるかどうかはわかりません。LayoutParams が変更されたので、そのために LayoutParams を設定する必要がありますか? 親のビューの次元を変更すると、子に引き継がれると思いました。
これがこの種のゲームでこれを行う正しい方法であるかどうかは、議論の余地がありますが、いずれにしても、それがどのように行われるかを知りたいです (私はそれができると思います..?)。どんな助けでも大歓迎です。