私は空のRelativeLayout
を持っています。レイアウトの高さと幅を取得する必要があります(親と一致するように設定されています)。私はオンラインで検索しようとしましたが、無駄です。これは私のコードです、助けてくれますか?アプリケーションを起動すると、getCoordinateメソッドがクラッシュします。私の英語には申し訳ありません。相対的なレイアウトのアンドロイドの尺度を取得しますか?
public class MainActivity extends AppCompatActivity {
Random rand = new Random();
int[] coordinate = new int[2];
public void getCordinate(final RelativeLayout layout){
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Ensure you call it only once :
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
coordinate[0] = layout.getMeasuredWidth();// width must be declare as a field
coordinate[1] = layout.getMeasuredHeight();// height must be declare as a fiel
}
});
}
public void makeButton(RelativeLayout play_area){
int button_x = rand.nextInt(coordinate[0]);
int button_y = rand.nextInt(coordinate[1]);
Button bomb = new Button(this);
bomb.setX((float)button_x);
bomb.setY((float)button_y);
play_area.addView(bomb);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout play_area = (RelativeLayout) findViewById(R.id.play_area);
play_area.measure(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
getCordinate(play_area);
Log.d("Coordinate", "Xmax: " + coordinate[0] + " Ymax: " + coordinate[1]);
//makeButton(play_area);
}
}
値を返す必要があり
と、単にあなたが起こると、おそらくあなたの問題のスタックトレースを含めているものを除い記述場合には有用であろう。 – ManoDestra
ビューでmeasure()を呼び出さないでください。それがレイアウトマネージャの仕事です。また、何かがクラッシュしている場合は、常にスタックトレースを投稿します。 –