我正在尝试以编程方式将带有 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>
<小时/>
现在,我需要补充一点,在升级到 Material 1.1 之前,编程方法是有效的。我仅使用 Material 组件。我该如何解决这个问题?
最佳答案
使用 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());
输出:
关于java - Android:以编程方式添加 TextInputLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60390492/