Android:以编程方式添加 TextInputLayout

use*_*789 2 java android material-design android-textinputlayout material-components-android

我正在尝试以编程方式将带有 EditText 的 TextInputLayout 添加到 LinearLayout。我的做法:

TextInputLayout textInputLayout = new TextInputLayout(new ContextThemeWrapper(getContext(), R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox));
textInputLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textInputLayout.setHintTextAppearance(R.style.Base_Widget_MaterialComponents_TextInputLayout_TextInputLayout);

TextInputEditText editText = new TextInputEditText(getContext());
editText.setHint("test");

textInputLayout.addView(editText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textInputLayout);
Run Code Online (Sandbox Code Playgroud)

然而,结果看起来非常错误:

越野车视图


奇怪的是,通过 XML 添加相同的 TextInputLayout 有效:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="kommentar"
    app:hintTextAppearance="@style/Base.Widget.MaterialComponents.TextInputLayout.TextInputLayout">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)

通过 xml 工作视图


现在,我需要补充一点,在升级到Material 1.1之前,编程方法是有效的。我只使用材料组件。我怎样才能解决这个问题?

Md.*_*man 7

使用 style 属性,您必须使用setBoxBackgroundMode()方法来使用OutlineBox样式。除此之外,您应该使用TextInputLayout'scontext来创建TextInputEditText. 检查以下:

textInputLayout.setBoxBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.white));
textInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);

//Must use context of textInputLayout
TextInputEditText editText = new TextInputEditText(textInputLayout.getContext());
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

  • 精彩的!```new TextInputEditText(textInputLayout.getContext());``` 行是我的情况的答案。多谢! (2认同)