Java Android:以编程方式添加TextInputLayout

Java Android:以编程方式添加TextInputLayout,java,android,material-design,android-textinputlayout,material-components-android,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(新的Linea

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

TextInputLayout TextInputLayout=new TextInputLayout(new ContextThemeWrapper(getContext(),R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox));
textInputLayout.setLayoutParams(新的LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_父项,LinearLayout.LayoutParams.WRAP_内容));
textInputLayout.setHintTextAppearance(R.style.Base\u Widget\u MaterialComponents\u textInputLayout\u textInputLayout);
textInputItemText editText=新的textInputItemText(getContext());
editText.setHint(“测试”);
textInputLayout.addView(编辑文本,新的LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_父项,LinearLayout.LayoutParams.WRAP_内容));
linearLayout.addView(文本输入布局);
但是,结果看起来非常糟糕:


奇怪的是,通过XML添加相同的TextInputLayout会起作用:




现在,我需要补充的是,在升级到Material 1.1之前,编程方法是有效的。我只使用材料组件。如何解决此问题?

使用style属性,您必须使用
setBoxBackgroundMode()
方法才能使用OutlineBox样式。除此之外,您还应该使用
TextInputLayout
context
来创建
textInputItemText
。检查以下内容:

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());
输出:


我花了数小时试图实现同样的目标,当我即将放弃时,我发现。下面引用gabrielemariotti的答案,这是针对材质按钮的,但同样适用于文本输入布局,可能还有其他材质组件

如果要创建具有自定义样式的自定义按钮,必须:

  • 在attrs.xml中定义属性

  • 在应用程序主题中为此新属性指定一个值:


您确定需要按程序进行吗?它使视图层逻辑更加复杂,应避免以编程方式添加/删除视图。我会将这个文本输入布局最初保持在XML中,但在需要时将可见性从GONE更改为VISIBLE,或者交换片段等。就像@Steyrix编写的那样,在XML中将可见性属性设置为invisible,然后在代码中使用.setVisibility(View.VISIBLE)更改它;我很清楚,不应该通过Java创建UI组件,但是,在这种情况下,它是必需的。太棒了!行
newtextinputtext(textInputLayout.getContext())是我的答案。谢谢!
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
        <item name="myButtonStyle">@style/AccentButtonStyle</item>
    </style>
    <style name="AccentButtonStyle" parent="Widget.MaterialComponents.Button">
        <item name="backgroundTint">@color/...</item>
        <item name="icon">@drawable/....</item>
        <item name="iconTint">@color/....</item>
    </style>