EditText保持过时的大小

时间:2015-08-27 14:21:20

标签: android xml

我的EditText中有一个RelativeLayout视图。除了一件事之外,它很好地包含了它的内容。我已将android:hint属性设置为某个默认文本,并且每当输入一些宽度小于提示的文本时,该框不会换行。它会保留在那里,因为它会环绕提示文本。使用android:text属性不是选项,因为您需要删除每个非常烦人的角色。我附上了三张图片和XML,两者都在关注。

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:id="@+id/editText"
    android:text="@string/textEditDefaultText"
    android:background="#4b010101"
    android:layout_centerVertical="true"
    android:layout_centerInParent="true" />

这里它应该更小,你可以在EditText的右边部分清楚地看到它。

或者更清楚,但文字更多:

如此处所示,当文本较长时,它会正确包装。

我正在使用Android 5.1。

3 个答案:

答案 0 :(得分:0)

每次更改文本时,您可以尝试使用自定义EditText或TextWatcher来调用requestLayout()吗?

我有理由相信,如果你使用两条或更多条线,EditText不会沿着水平方向收缩。

为什么你想让EditText改变宽度呢?也许有不同的解决方案?

答案 1 :(得分:0)

我认为这是一个错误。该提示不应该是布局的一部分

  

提示当前不参与确定视图的大小。   (source

答案 2 :(得分:0)

所以它似乎是一个bug,正如F43nd1r建议的那样。我已相应提出了一项请求here。但是,我们可以通过一起攻击自定义视图来为此编写快速而肮脏的修复程序。因此,创建一个新的Java类,XML文件并使用自定义EditText替代正常EditText修复了该问题。

public class CustomEditText extends EditText {
    public CharSequence hint = null;

    public CustomEditText(Context context) {
        super(context);
    }

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

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onTextChanged(CharSequence text, int start,
                              int lengthBefore, int lengthAfter) {
        if(hint == null) {
            hint = this.getHint();
            this.setHint("");
        } else {
            if(this.getText().length == 0) {
                this.setHint(hint);
                hint = null;
            }
        }

        this.requestLayout();
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }
}

位于layouts文件夹中的XML文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <thoughts.dasnacl.thoughts.CustomEditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</FrameLayout>