0

我有一个空的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);

}
}
4

1 回答 1

0

你不应该调用 measure()。您可以只调用 .setLayoutParams(width, height) 来设置视图以匹配父级的宽度/高度。

并且简单地在视图上调用 .getMeasuredWidth() (或高度)应该返回它们的宽度/高度值

于 2016-04-06T22:01:04.833 回答