【问题标题】:How Can I set style to TextInputLayout by dynamically in android?如何在android中动态设置样式为TextInputLayout?
【发布时间】:2021-04-09 20:00:32
【问题描述】:

我想通过动态创建 TexInputLayout。我可以使用以下代码块创建 TextInputLayout :

TextInputLayout til = new TextInputLayout(this);
EditText et = new EditText(this);
til.addView(et);
et.setHint("Enter");
information.addView(til);

信息是我在项目中使用的线性布局的名称。

但我想更改我动态创建的 TextInputLaout 的样式,我想使用 @style/Widget.MaterialComponents.TextInputLayout.OutlinedBox。

我尝试了以下代码块来更改样式:

TextInputLayout till= new TextInputLayout(new ContextThemeWrapper(this, 
 R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox));
 EditText et = new EditText(this);
 til.addView(et);
 et.setHint("Enter");
 information.addView(til);

但这些代码不起作用。如何为我动态创建的 TextInputLayout 添加样式?

【问题讨论】:

    标签: android styles dynamically-generated material-components-android android-textinputlayout


    【解决方案1】:

    ContextThemeWrapper 的第二个参数是主题覆盖,而不是样式。

    您可以在attrs.xml 中定义自定义属性:

    <attr name="customTextInputStyle" format="reference" />
    

    然后在您的应用主题中:

    <style name="AppTheme" parent="Theme.MaterialComponents.*">
        <!-- ..... -->
        <item name="customTextInputStyle">@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox</item>
    </style>
    

    最后:

        TextInputLayout til = new TextInputLayout(this,null,R.attr.customTextInputStyle);
        til.setHint("Label");
        TextInputEditText et = new TextInputEditText(til.getContext());  //important: get the themed context from the TextInputLayout
        til.addView(et);
        buttonsLayout.addView(til);
    

    【讨论】:

    • 它不起作用:(我在值中创建了一个 attrs.xml 文件并添加您的代码块。在我将您的样式代码添加到样式文件夹之后。我不得不更改样式的名称。但是我的问题仍然存在:(
    • 我的回答和你分享的一样,我做错了什么?
    • @Neo 主题的名称没有问题,只需使用您的主题添加 customTextInputStyle 属性。您使用的是材质组件主题吗?你用的是 1.3.0 吗?
    • 我使用的是 1.1.0
    • 当我更新材料的版本时,我的问题仍然存在,并且我之前创建的 TextInputlayouts 被破坏了。
    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多