Android 获取相对布局的度量?
我有一个空的Android 获取相对布局的度量?,android,android-layout,android-relativelayout,android-studio-2.0,Android,Android Layout,Android Relativelayout,Android Studio 2.0,我有一个空的RelativeLayout。我必须获得布局的高度和宽度(设置为匹配父级)。我曾尝试在网上搜索,但没有结果。这是我的密码,你能帮我吗?当我启动应用程序时,它在getCoordinate方法中崩溃。对不起我的英语 public class MainActivity extends AppCompatActivity { Random rand = new Random(); int[] coordinate = new int[2]; public void getCordinat
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)将视图设置为与父视图的宽度/高度相匹配
只需在视图上调用.getMeasuredWidth()(或height)就可以返回它们的宽度/高度值如果您描述发生了什么异常,并可能在问题中包含堆栈跟踪,这将非常有用。不要在视图上调用Measured()。这是布局经理的工作。还有,是的,如果有什么东西崩溃了,总是发布堆栈跟踪。我的布局必须适应显示尺寸。当relativelayput被调整时,我必须以dp的形式获取此的维度,.getMeasureWidth()每0返回一次