获取相对布局android的度量



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

您不应该调用measure()。您可以调用.setLayoutParams(width,height)将视图设置为与父视图的width/height相匹配。

只需在视图上调用.getMeasuredWidth()(或height)就可以返回它们的宽度/高度值

最新更新