如何从活动中访问视图的尺寸?

时间:2011-06-15 13:11:47

标签: android android-layout

访问myView.getWidth()getHeight()始终返回零,我理解这是因为我在提出意见之前过早地调用它们。

但是我如何从活动中访问视图的大小?我看不到要覆盖的方法,而且文档也没有建议我可以捕获的lifecycle事件。

===================================

谢谢坦纳。这是我使用的代码,工作正常。

LinearLayout root = (LinearLayout)findViewById(R.id.main);
Display d = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = d.getWidth();
int screenHeight = d.getHeight();
root.measure(screenWidth, screenHeight);
View myView = findViewById(R.id.myView);
int width = myView.getMeasuredWidth();

2 个答案:

答案 0 :(得分:1)

看看这个:http://developer.android.com/guide/topics/ui/how-android-draws.html

您是否尝试过在视图中调用measure()然后getMeasuredWidth()

请注意,还有方法requestLayout()

答案 1 :(得分:0)

在将布局设置为活动的内容视图后,您应该访问维度。 只需使用findViewById(id)通过id找到它,然后调用我的View.getWidth()