我有一个空的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);
}
}
答案 0 :(得分:0)
你不应该叫measure()。您可以调用.setLayoutParams(width,height)来设置视图以匹配父级的宽度/高度。
只需在视图上调用.getMeasuredWidth()(或高度)即可返回其宽度/高度值