java - Android:以编程方式添加 TextInputLayout

标签 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);

但是,结果看起来非常错误:

buggy view

<小时/>

奇怪的是,通过 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>

working view via xml

<小时/>

现在,我需要补充一点,在升级到 Material 1.1 之前,编程方法是有效的。我仅使用 Material 组件。我该如何解决这个问题?

最佳答案

使用 style 属性,您必须使用 setBoxBackgroundMode() 方法才能使用 OutlineBox 样式。除此之外,您应该使用 TextInputLayoutcontext 来创建 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());

输出:

enter image description here

关于java - Android:以编程方式添加 TextInputLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60390492/

相关文章:

android - 使 WakefulIntentService 等待位置回调被调用

java - 尝试连接 sphero 时发生错误

c# - 使用 MahApp.Metro 主题自定义 SaveFileDialog

java - Vertx 不获取外部 conf 文件

java - SQLite中更新语句的问题

android - 创建文件夹而不是文件

android - Material SearchView 实现错误

javascript - Angular Material 输入单击时选择全部?

java.text.ParseException : Unparseable date: 异常

java - 从 XSD XML 模式(使用 JAXB)生成示例 JSON 文档的快速而简单的方法是什么?