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)
现在,我需要补充一点,在升级到Material 1.1之前,编程方法是有效的。我只使用材料组件。我怎样才能解决这个问题?
使用 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)
输出:
| 归档时间: |
|
| 查看次数: |
1146 次 |
| 最近记录: |