【问题标题】:Android - i can not set EditText layout width programmaticallyAndroid - 我无法以编程方式设置 EditText 布局宽度
【发布时间】:2021-06-21 14:53:31
【问题描述】:

我尝试了两种方法来设置 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());

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

【问题讨论】:

    标签: android android-layout layout textview


    【解决方案1】:

    正如@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);
                }
            });
    

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

    【讨论】:

      【解决方案2】:

      这里有很多不同的事情需要指出。 您没有为您的视图设置任何文本(在我们在这里看到的)这会阻止我们提供更好的帮助

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

      在第二个示例中,我们不知道您何时调用该代码,如果它在 onCreate 或其他内部,则视图尚未测量/布局,并且它们的大小不可靠(在大多数情况下它们返回 0)。

      通过在它们之间设置相同的宽度来说明您正在寻找什么也是有意义的,也许有人可能会提供更好的解决方案

      【讨论】:

      • 第一个EditText的长度大于第二个。第一个:类名第二个:讲师我尝试在 onCreate 和 onStart 方法中运行第二个代码。正如你所说,它返回 0。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 2016-11-10
      • 2012-03-02
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多