在运行时没有办法改变任何视图或布局的主题,因为主题和样式是在创建视图时递归应用的(主题也适用于布局的子视图)。
但是,您可以在创建视图之前使用XML布局或编程方式更改该主题。
编程方式:
方法1 - 使用android.view.ContextThemeWrapper
包装Context
并以编程方式创建TextInputLayout
并使用它。
TextInputLayout layout = new TextInputLayout(new ContextThemeWrapper(getContext(), R.style. TextInputLayoutTheme))
方法2 - 扩展TextInputLayout并使用自己的布局。将ContextThemeWrapper
作为上下文传递。
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布局中使用MyTextInputLayout
使用XML布局:
1) 在attrs.xml
文件中,创建名为textInputLayoutTheme
的新属性
<attr name="textInputLayoutTheme" format="reference"/>
2) 在styles.xml
文件的AppTheme
中,将@style/TextInputLayoutTheme
设置为textInputLayoutTheme
。
<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>
3) 在你的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
的主题,而不是 TextInputLayoutTheme
。