什么时候我可以安全地查询View的尺寸?

时间:2013-10-17 17:42:06

标签: 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/missingpuz"
     android:clickable="true"
     android:onClick="pickShapes"
     />

我需要知道特定的“fill_parent”最终会是什么。我尝试使用包含我的自定义视图的布局在活动的onCreate方法中获取此信息:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_puzzle_picker);
    // Show the Up button in the action bar.
    setupActionBar();
    int a = findViewById(R.id.pickshapes).getMeasuredHeight();
    int b = findViewById(R.id.pickshapes).getHeight();

在这种情况下,ab都返回值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);
}

此处ab都提供了有效的维度...我不想等待“onClick”事件,但我希望尽快获得维度。我已经尝试覆盖onStart()onResume()来检查维度,但在这两种情况下我仍然得到0。

所以我的问题是,在Android Activity启动流程中,我是第一个可以获得View实际大小的地方吗?我希望能够尽快获得高度/宽度,并且我想在用户有机会与环境交互之前做到这一点。

1 个答案:

答案 0 :(得分:2)

在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,因为这是您选择的内容。)