Snake
Snake

Reputation: 14638

finding width of textView before it is drawn when it is created dynamically

I have an activity that has imageview1 at the bottom right. After the activity starts and onWindowFocusChanged is called, I want to dynamaically create an textView and place it beside the imageview1 (to the left). I know I can use set the location of textView by modifying its layoutParam but to align it properly I do the following

param.setMargins(0, imageView1.getTop(), rootLayout.getWidth()-imageView1.getLeft()-textView.getWidth, 0);

. The problem is I can't find out the width of textView because it has not been drawn yet. How can I get around this?

Upvotes: 2

Views: 58

Answers (2)

Bracadabra
Bracadabra

Reputation: 3659

You can ask view to measure itself, but you should specify constrains. For example:

final Button button = new Button(this);
button.setText("Button");
button.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
Log.d("Test", "measured width: " + button.getMeasuredWidth());
Log.d("Test", "measured height: " + button.getMeasuredHeight());

Then you've got:

11-09 10:33:14.316 14959-14959/com.madcucumber.testapplication D/Test: measured width: 264
11-09 10:33:14.316 14959-14959/com.madcucumber.testapplication D/Test: measured height: 144

Upvotes: 1

SuperFrog
SuperFrog

Reputation: 7674

Maybe using onSizeChanged will be usefull for you:

protected void onSizeChanged (int w, int h, int oldw, int oldh)

Added in API level 1 This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0.

Parameters

w Current width of this view.

h Current height of this view.

oldw Old width of this view.

oldh Old height of this view.

http://developer.android.com/reference/android/view/View.html#onSizeChanged(int, int, int, int)

You can offcourse use TreeObserver:

ViewTreeObserver vto = imageView1.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.image1.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = imageView1.getMeasuredWidth();
        int height = imageView1.getMeasuredHeight(); 
    } 
});

Upvotes: 0

Related Questions