首页 > 解决方案 > TextInputLayout 材质组件问题:此组件上的样式要求您的应用主题为 Theme.MaterialComponents(或后代)

问题描述

我在使用 TextInputLayout 实现 Material 设计时遇到问题,我知道解决方案是让您的活动主题继承 Material Component Theme 之一,但这会给我的大多数应用程序主题带来这样的变化,并且需要更多时间来重构它。我想要的是仅针对应用程序上这个特定的 TextInputLayout 的材料设计。

这是我尝试过的

<com.google.android.material.textfield.TextInputLayout
                android:id="@+id/firstName"
                style="@style/CustomInputStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginEnd="5dp"
                android:layout_weight="1"
                app:errorEnabled="true">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/fname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/first_name"
                    android:inputType="text|textCapWords"
                    android:nextFocusDown="@id/lname"
                    android:textSize="12sp" />

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




<style name="CustomInputStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
            <item name="boxStrokeWidth">2dp</item>
            <item name="hintTextColor">@color/colorAccent</item>
            <item name="boxStrokeColor">@android:color/white</item>
            <item name="android:colorAccent">@color/colorAccent</item>
            <item name="android:textColorHint">@color/colorAccent</item>
        </style>

错误 : Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).

我们不能这样做而不是覆盖整个应用程序/活动主题吗?我想要的只是在特定的片段上使用它。

标签: androidmaterial-designandroid-themematerial-components-android

解决方案


我只是注意到可以将 Material Components 主题放在 XML 布局的根视图中,然后您现在可以应用该样式而不会出现任何错误。

在父/根视图中添加这个

android:theme="@style/Theme.MaterialComponents.Bridge"

然后将样式应用到子视图 TextInputLayout

<com.google.android.material.textfield.TextInputLayout
            android:id="@+id/firstName"
            style="@style/CustomInputStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="5dp"
            android:layout_weight="1"
            app:errorEnabled="true">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/fname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/first_name"
                android:inputType="text|textCapWords"
                android:nextFocusDown="@id/lname"
                style="@style/CustomEditText"
                android:textSize="12sp" />

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

推荐阅读