Android - i can not set EditText layout width programmatically

Viewed 244

i tried two way to set width of the EditText, but i got no proper result. the xml file contains:

<TextView
    android:id="@+id/textView1"
    style="@android:style/Widget.AutoCompleteTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:hint="@string/classname"
    android:textSize="25sp" />

<TextView
    android:id="@+id/textView2"
    style="@android:style/Widget.AutoCompleteTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:hint="@string/teacher"
    android:textSize="25sp" />

the first way:

TextView tw1 = (TextView) findViewById(R.id.textView1);
TextView tw2 = (TextView) findViewById(R.id.textView2);
tw2.setLayoutParams(new LinearLayout.LayoutParams(tw1.getLayoutParams().width, LinearLayout.LayoutParams.WRAP_CONTENT));

the second way:

TextView tw1 = (TextView) findViewById(R.id.textView1);
TextView tw2 = (TextView) findViewById(R.id.textView2);
tw2.setWidth(tw1.getWidth());

While the first code does not work at all, the second code gives an unrelated result. What is my mistake or what is the correct way of doing this?

2 Answers

As @Amin said, layout width was zero when using getWidth in the onCreate or onStart or onResume methods. I found the solution like that:

tw1.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tw1.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int theWidth = tw1.getWidth();
                tw2.setWidth(theWidth);
            }
        });

This method is called when the view object's properties change. For this problem it is a good solution i think.

There are a lot of different things to point out here. You haven't set any text to your view (in what we see here) which is prevent us from helping better

In the first method you are copying the tw1 layoutParams's width/height (which is wrap content) to tw2, in other words nothing effective

In the second example we do not know when you call that code, if it is inside onCreate or something, views haven't been measure/layout yet and their sizes are not reliable (in most cases they return 0).

Also it would make sense to say what you're seeking by setting same width among them, maybe someone may come with a better solution

Related