Android - 我无法以编程方式设置 EditText 布局宽度

Android - i can not set EditText layout width programmatically

我尝试了两种方法来设置 EditText 的宽度,但没有得到正确的结果。 xml 文件包含:

<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" />

第一种方式:

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

第二种方式:

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

虽然第一个代码根本不起作用,但第二个代码给出了不相关的结果。我的错误是什么或者这样做的正确方法是什么?

这里有很多不同的地方需要指出。 您还没有为您的视图设置任何文本(在我们这里看到的),这使我们无法提供更好的帮助

在第一种方法中,您将 tw1 layoutParams 的 width/height(包装内容)复制到 tw2,换句话说没有任何效果

在第二个示例中,我们不知道您何时调用该代码,如果它在 onCreate 之类的内部,视图尚未 measure/layout 并且它们的大小不可靠(在大多数情况下它们 return0).

此外,通过在它们之间设置相同的宽度来说明您正在寻找的内容是有意义的,也许有人会提出更好的解决方案

正如@Amin 所说,在 onCreate 或 onStart 或 onResume 方法中使用 getWidth 时布局宽度为零。我找到了这样的解决方案:

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

当视图对象的属性改变时调用此方法。对于这个问题,我认为这是一个很好的解决方案。