Greenhorn
Greenhorn

Reputation: 769

Setting the width of EditText

I am setting the width of EditText element to fill_parent in XML file, but when accessing it from code, it returns 0. What I want, is the actual width of that element at run time. How could I do it.

Upvotes: 0

Views: 1789

Answers (3)

Kevin Coppock
Kevin Coppock

Reputation: 134664

I'll refer you to a previous answer on this topic that should be helpful:

How to retrieve the dimensions of a view?

Upvotes: 0

evilone
evilone

Reputation: 22740

You could solve this by creating a custom View and override the onMeasure() method. If you always use "fill_parent" for the layout_width in your xml then the widthMeasureSpec parameter that is passed into the onMeasusre() method should contain the width of the parent.

public class MyCustomView extends EditText {

public MyCustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
}
}   

Your XML would look something like this:

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <view
        class="com.company.MyCustomView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

Upvotes: 1

Aleadam
Aleadam

Reputation: 40381

Use getMeasuredWidth(): http://developer.android.com/reference/android/view/View.html#getMeasuredWidth%28%29

Read also here:

When a View's measure() method returns, its getMeasuredWidth() and getMeasuredHeight() values must be set, along with those for all of that View's descendants. A View's measured width and measured height values must respect the constraints imposed by the View's parents. This guarantees that at the end of the measure pass, all parents accept all of their children's measurements. A parent View may call measure() more than once on its children. For example, the parent may measure each child once with unspecified dimensions to find out how big they want to be, then call measure() on them again with actual numbers if the sum of all the children's unconstrained sizes is too big or too small (i.e., if the children don't agree among themselves as to how much space they each get, the parent will intervene and set the rules on the second pass).

http://developer.android.com/guide/topics/ui/how-android-draws.html

Upvotes: 2

Related Questions