以编程方式设置TextInputLayout主题

时间:2018-01-25 13:30:08

标签: android xml android-layout android-textinputlayout

有没有办法在Android中以编程方式更改TextInputLayout的主题。 如果我有以下TextInputLayout for ex。:

<android.support.design.widget.TextInputLayout
    android:id="@+id/label"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:paddingTop="16dp"
    android:theme="@style/TextInputLayoutTheme"
    app:errorTextAppearance="@style/Error">

    <android.support.v7.widget.AppCompatEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="8dp"
        android:paddingTop="8dp"/>
</android.support.design.widget.TextInputLayout>

我可以通过编程方式以某种方式将此行android:theme="@style/TextInputLayoutTheme"更改为其他主题吗?

1 个答案:

答案 0 :(得分:5)

没有方式可以在运行时更改任何视图或任何布局的主题。由于主题和样式是在创建视图期间应用的,因此是递归的。 (主题还应用了布局的子视图)

但是,您可以在使用XML布局或以编程方式创建视图之前更改该主题。

编程:

方法1 - 以编程方式创建<a href="{{ post.url }}">并将TextInputLayoutContext一起打包并使用。

android.view.ContextThemeWrapper

方法2 - 扩展TextInputLayout并使用您自己的布局。将TextInputLayout layout = new TextInputLayout(new ContextThemeWrapper(getContext(), R.style. TextInputLayoutTheme)); 作为上下文传递。

ContextThemeWrapper

现在,您可以在XML布局中使用public class MyTextInputLayout extends TextInputLayout { public MyTextInputLayout(Context context) { super(new ContextThemeWrapper(context, R.style.AppTheme)); } public MyTextInputLayout(Context context, AttributeSet attrs) { super(new ContextThemeWrapper(context, R.style.AppTheme), attrs); } public MyTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(new ContextThemeWrapper(context, R.style.AppTheme), attrs, defStyleAttr); } }

使用XML布局:

1)MyTextInputLayout文件中,创建名为attrs.xml的新属性

textInputLayoutTheme

2)<attr name="textInputLayoutTheme" format="reference"/> AppTheme个文件中,将styles.xml设置为@style/TextInputLayoutTheme

textInputLayoutTheme

3)<resources> <style name="AppTheme" parent="PARENT_THEME"> <item name="textInputLayoutTheme">@style/TextInputLayoutTheme</item> </style> <style name="AppTheme.Secondary"> <item name="textInputLayoutTheme">@style/TextInputLayoutTheme_Secondary</item> </style> </resources> 文件中,将layout.xml设为?attr/textInputLayoutTheme主题

TextInputLayout

现在,当您将应用主题从<android.support.design.widget.TextInputLayout android:id="@+id/label" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:paddingTop="16dp" android:theme="@?attr/textInputLayoutTheme" app:errorTextAppearance="@style/Error"> 更改为AppTheme AppTheme.Secondary时,将用作TextInputLayoutTheme_Secondary而非TextInputLayout的主题。< / p>