【问题标题】:Get measure of relative layout android?获取相对布局android的度量?
【发布时间】:2016-04-06 19:20:50
【问题描述】:

我有一个空的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()。这是布局管理器的工作。另外,是的,如果发生崩溃,请始终发布堆栈跟踪。

标签: android android-layout android-relativelayout android-studio-2.0


【解决方案1】:

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

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

【讨论】:

  • 我的布局必须适应显示尺寸。当 relativelayput 被调整时,我必须得到这个 dp 中的尺寸,.getMeasureWidth() 每 0 次返回一次
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
相关资源
最近更新 更多