android - 如何为自定义 TextInputLayout 设置默认样式

标签 android kotlin android-theme material-components-android android-textinputlayout

我想创建一个具有默认样式的自定义 TextInputLayout。但未应用样式。

class AutoCompleteTextInputLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.style.AppTheme_TextInputLayout_DropdownMenu
): TextInputLayout(context, attrs) {

    init {
        context.inflater.inflate(R.layout.auto_complete_text_input_layout, this,true) 
    }

}
<style name="AppTheme.TextInputLayout.DropdownMenu" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu">
    <item name="endIconMode">dropdown_menu</item>
</style>

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</merge>

我不希望默认情况下为所有 TextInputLayout 应用此样式,因为我已经有如下样式:

    <style name="AppTheme" parent="Theme.MaterialComponents.Light">
        <item name="textInputStyle">@style/AppTheme.TextInputLayout</item>>
    </style>

预先感谢您的帮助

最佳答案

您不能将构造函数与 R.style.AppTheme_TextInputLayout_DropdownMenu 一起使用,因为 TextInputLayout3rd 参数 不是样式,但属性主题为 R.attr.textInputStyle

你可以使用类似的东西:

public class AutoCompleteTextInputLayout @JvmOverloads constructor(
        context: Context, 
        attrs: AttributeSet? = null, 
        defStyleAttr: Int = R.attr.textInputStyle
) : TextInputLayout(ContextThemeWrapper(context, R.style.Custom_Theme),
                    attrs, defStyleAttr) { ...  }

自定义主题:

<style name="Custom.Theme" parent="">
   <item name="textInputStyle">@style/AppTheme.TextInputLayout.DropdownMenu</item>
</style>

通过这种方式,您将创建一个具有指定主题 (Custom.Theme) 的新上下文包装器。此主题仅由自定义小部件 AutoCompleteTextInputLayout 使用。
这意味着其他 TextInputLayout 继续使用默认样式(由 AppTheme 中的属性 textInputStyle 定义)。

例子:

<AutoCompleteTextInputLayout>

    <com.google.android.material.textfield.TextInputEditText/>

</AutoCompleteTextInputLayout>

<com.google.android.material.textfield.TextInputLayout>

     <com.google.android.material.textfield.TextInputEditText/>

</com.google.android.material.textfield.TextInputLayout>

enter image description here

关于android - 如何为自定义 TextInputLayout 设置默认样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64378135/

相关文章:

java - 我无法理解这个 MediaPlayer 错误 : MediaPlayerNative: stop called in state 0, mPlayer(0x7efba92280)

kotlin - 在不使用正则表达式的情况下有效地将 Kotlin 字符串分解为固定长度的子字符串

java - arrayListOf(),sortedWith,compareBy与Java等效

android - 无法设置 colorControlNormal 和 android :textColor in style

android - 更改工具栏中的标题颜色?

android - 如何调试失败的 Android Gradle 构建?

android - 自定义 ViewGroup 中的 View 在大小更改后未呈现

android - com.example.myapplication.ui.home.HomeFragment上的kotlin.KotlinNullPointerException

android-studio - Java 和 Kotlin for 循环语法之间的区别?

android - 如何在不影响其弹出菜单的情况下向微调器添加边框