如何在Android中动态设置样式为TextInputLayout? [英] How Can I set style to TextInputLayout by dynamically in android?
问题描述
我想通过动态创建TexInputLayout.我可以使用以下代码块创建TextInputLayout:
I want to create TexInputLayout by dynamically. I can create TextInputLayout using following code block :
TextInputLayout til = new TextInputLayout(this);
EditText et = new EditText(this);
til.addView(et);
et.setHint("Enter");
information.addView(til);
信息是我在项目中使用的线性布局的名称.
information is name of my linear layout which I use in the project.
但是我想更改通过动态创建的TextInputLaout的样式,我想使用@ style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.
But I want to change style of the TextInputLaout which I created by dynamically, I want to use @style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.
我尝试了以下代码块来更改样式:
I tried the following code block to change style :
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添加样式?
but these code is not working. How can add style to TextInputLayout which I created dynamically ?
推荐答案
ContextThemeWrapper
的第二个参数是主题叠加层,而不是样式.
The 2nd parameter of the ContextThemeWrapper
is a theme overlay, not a style.
您可以在 attrs.xml
中定义一个自定义属性:
You can define in attrs.xml
a custom attribute:
<attr name="customTextInputStyle" format="reference" />
然后在您的应用主题中:
then in your app theme:
<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);
这篇关于如何在Android中动态设置样式为TextInputLayout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!