gpt4 book ai didi

android - 以编程方式设置 TextInputLayout 主题

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:22 25 4
gpt4 key购买 nike

有没有办法在 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" 以编程方式更改为另一个主题?

最佳答案

无法运行时更改任何 View 或任何布局的主题。因为主题和样式是在 View 创建期间递归应用的。 (主题也适用于布局的 subview )

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

以编程方式:

方法 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

关于android - 以编程方式设置 TextInputLayout 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48444048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com