添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Android - 我不能以编程方式设置EditText的布局宽度

2 人关注

我尝试了两种方法来设置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
Talha Ç
Talha Ç
发布于 2021-03-25
2 个回答
Talha Ç
Talha Ç
发布于 2021-03-25
已采纳
0 人赞同

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

当视图对象的属性发生变化时,这个方法被调用。对于这个问题,我想这是一个很好的解决方案。

Amin
Amin
发布于 2021-03-25
0 人赞同