bue*_*las 6 xml android android-layout android-textinputlayout
有没有一种方法可以在Android中以编程方式更改TextInputLayout的主题。如果我有以下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="@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>
Run Code Online (Sandbox Code Playgroud)
我可以以android:theme="@style/TextInputLayoutTheme"
编程方式将此行更改为另一个主题吗?
有没有办法改变任何视图或在任何布局的主题运行。由于主题和样式是在视图创建期间递归应用的。(主题也适用于布局的子视图)
但是,您可以在使用XML布局或以编程方式创建视图之前更改该主题。
方法1 -创建TextInputLayout
与包装编程Context
与android.view.ContextThemeWrapper
和使用。
TextInputLayout layout = new TextInputLayout(new ContextThemeWrapper(getContext(), R.style. TextInputLayoutTheme));
Run Code Online (Sandbox Code Playgroud)
方法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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以MyTextInputLayout
在XML布局中使用
1)在attrs.xml
文件中,创建名为textInputLayoutTheme
<attr name="textInputLayoutTheme" format="reference"/>
Run Code Online (Sandbox Code Playgroud)
2)在您AppTheme
的styles.xml
文件中,将您设置@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>
Run Code Online (Sandbox Code Playgroud)
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">
Run Code Online (Sandbox Code Playgroud)
现在,当你从改变你的应用程序的主题AppTheme
,以AppTheme.Secondary
TextInputLayoutTheme_Secondary
将作为你的一个主题TextInputLayout
,而不是TextInputLayoutTheme
。
归档时间: |
|
查看次数: |
2319 次 |
最近记录: |