我试图以编程方式将带有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);
但是,结果看起来异常错误:
奇怪的是,通过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>
现在,我需要补充一下,在升级到材料1.1之前,程序化方法已经奏效。我仅使用材料组件。我怎样才能解决这个问题?
最佳答案
使用style属性,您必须使用setBoxBackgroundMode()
方法来使用OutlineBox样式。除此之外,您还应该使用TextInputLayout
的context
创建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());
输出: