0

Suppose you wanted to create a subclass of RelativeLayout and inside the class definition you wanted to get its width and height. (The subclass is added via xml to the application, match_parent, match_parent).

I've tried following code, but it toasts me 0:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // TODO Auto-generated method stub
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Toast.makeText(context, "" + this.getWidth(), Toast.LENGTH_SHORT).show();
}

And this gives me -1:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // TODO Auto-generated method stub
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Toast.makeText(context, "" + this.getLayoutParams().width, Toast.LENGTH_SHORT).show();
}

So what are my options, or onMeasure() only works for subclasses of anroid.view.View?

EDIT: I know I can call onWindowFocusChanged() in the Activity, but can I get the size of the RelativeLayout subclass in its class definition, so that I don't need to couple the two classes just because of this?

Kovács Imre
  • 715
  • 2
  • 7
  • 17

1 Answers1

1

You can override onLayout method or onSizeChanged. Also you can use ViewTreeOserver. If you want to know results of onMeasure method use getMeasuredWidth/Height instead of getWidth/Height inside onMeasure.

Community
  • 1
  • 1
Leonidos
  • 10,482
  • 2
  • 28
  • 37