Java 何时可以安全地查询视图';s维度?
我试图在我的活动中抓住视图的维度。该视图是一个简单的自定义视图,它扩展了ImageView:Java 何时可以安全地查询视图';s维度?,java,android,runtime,android-imageview,Java,Android,Runtime,Android Imageview,我试图在我的活动中抓住视图的维度。该视图是一个简单的自定义视图,它扩展了ImageView: <com.example.dragdropshapes.CustomStrechView android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/border" android:src="@drawable/mis
<com.example.dragdropshapes.CustomStrechView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/border"
android:src="@drawable/missingpuz"
android:clickable="true"
android:onClick="pickShapes"
/>
在这种情况下,a
和b
都返回0的值。稍后,自定义视图将用作按钮(它有一个onClick处理程序),因此我想再次尝试获取处理程序中的大小:
public void pickShapes(View view){
Intent intent = new Intent(this, ShapesActivity.class);
int a = findViewById(R.id.pickshapes).getMeasuredHeight();
int b = findViewById(R.id.pickshapes).getHeight();
startActivity(intent);
}
这里a
和b
都给出了有效的维度。。。我不想等待“onClick”事件,但是,我希望尽快获得维度。我已经尝试重写onStart()
和onResume()
来检查维度,但在这两种情况下,我仍然得到0
所以我的问题是,在Android活动启动流程中,哪里是第一个可以获得视图实际大小的地方?我希望能够尽快获得高度/宽度,并且我希望在用户有机会与环境交互之前完成 Android中有一个相当有用的东西叫做
ViewTreeObserver
。我已经做了很多次你需要做的事情。正如您所发现的,您至少需要等到度量周期完成。请尝试以下操作:
...
setContextView(R.layout.activity_puzzle_picker);
final View view = findViewById(R.id.pickshapes);
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if(height > 0) {
// do whatever you want with the measured height.
setMyViewHeight(height);
// ... and ALWAYS remove the listener when you're done.
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
...
(请注意,您没有在XML中设置视图的id…我使用的是
R.id.pickshapes
,因为这是您选择的。)这非常酷,几乎正是我需要的。。。知道在API级别16之前做了什么而不是removeOnGlobalLayoutListener()
吗?找到了它,上的在Global
的另一边,对旧API(即removeGlobalLayOutliner()
)进行调整,并检查SDK版本,我准备好了!非常感谢!
...
setContextView(R.layout.activity_puzzle_picker);
final View view = findViewById(R.id.pickshapes);
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if(height > 0) {
// do whatever you want with the measured height.
setMyViewHeight(height);
// ... and ALWAYS remove the listener when you're done.
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
...