0

I'm trying to grab the dimensions of a view in my activity. The view is a simple custom view which extends an 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"
     />

I need to know what the specific "fill_parent" ends up being. I attempted to get this information during the onCreate method of the Activity using the layout containing my custom views:

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();

In this case, both a and b return a value of 0. Later, the custom view will be used as a button (it has an onClick handler) so I thought to try again to get the size in the handler:

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);
}

Here a and b both give valid dimensions... I don't want to wait for a "onClick" event however, I want to get the dimensions as soon as possible. I've tried Overriding both onStart() and onResume() to check the dimensions as well, but in both cases I still get 0.

So my question is, where in the Android Activity start up flow, is the first place I can get the actual size of a View? I want to be able to get the height/width as soon as I can, and I want to do it before the user has a chance to interact with the environment.

4

1 回答 1

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

于 2013-10-17T17:59:59.163 回答