0

您好,我有兴趣在加载布局后使用 android 获取布局的宽度和高度,然后根据这些测量结果为我的游戏运行的 Android 设备创建具有适当尺寸的图片、文本框和按钮!这怎么可能 ?我应该在哪个函数中输入以下代码:

layout.getWidth();
layout.getHeight();

所以它不会返回 0 ?在表单实际加载之前实现上述获取宽度和高度会更方便,但据我所知,这要困难得多这是我迄今为止试图获得这些测量值的代码:

protected void onStart() {
    super.onStart();
    txt = (TextView) findViewById(R.id.textView);
    img = (ImageView) findViewById(R.id.imageView2);
    layout = (RelativeLayout) findViewById(R.id.MyLayout);
    GameHandler();
}

public void GameHandler()
{
    txt.setText(""+layout.getHeight()) ; //this always returns 0
}

谢谢您的帮助 :)

4

2 回答 2

0

试试看

layoutView.post(new Runnable() {

        @Override
        public void run() {
            // Get width and height here
        }
    });
于 2014-07-22T12:18:47.230 回答
0

OnGlobalLayoutListener 是迄今为止我发现的最好的回调。

layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
         // This is a async callback. get the view size here.
         txt.setText(""+layout.getHeight()) ;
    }
});

layout 必须是类变量,否则必须使用 final 修饰符。

于 2014-07-22T12:16:41.807 回答