android - 为什么我的 android 按钮没有显示正确的背景?
问题描述
我正在尝试为我的 android 应用程序设置一个片段的样式,当我应用android:background
xml 属性时,它被忽略了。这是我得到的与正确样式的编辑文本相反的结果。
背景不正确的按钮:
具有正确背景的 EditText:
这是我的按钮的 XML:
<com.google.android.material.button.MaterialButton
android:id="@+id/register_fragment_submit_button"
style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
android:text="@string/register_register_button"
android:layout_marginTop="@dimen/register_fragment_submit_button_margin_top"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/register_button_bg"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/register_email_edittext" />
这是我正确样式的 EditText 的代码:
<EditText
android:id="@+id/register_email_edittext"
style="@style/register_fragment_edittext"
android:layout_marginTop="@dimen/register_fragment_email_edittext_margin_top"
android:autofillHints="@string/register_screen_email_autofill"
android:hint="@string/register_email_edittext_hint"
android:inputType="textEmailAddress"
android:text="@={viewmodel.newUserEmail$app_debug}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/register_password_edittext" />
这是它的风格:
<style name="register_fragment_edittext">
<item name="android:paddingLeft">@dimen/register_fragment_edittext_padding_left</item>
<item name="android:background">@drawable/edittext_background</item>
<item name="android:layout_width">@dimen/register_fragment_edittext_width</item>
<item name="android:layout_height">@dimen/edit_text_height</item>
<item name="android:textColorHint">@color/colorAccent</item>
</style>
如果有人好奇,我会将可绘制的 XML 代码留在底部。如果重要,我将其放入我的应用程序级 build.gradle 文件中进行材料设计:
implementation 'com.google.android.material:material:1.2.0'
有人有什么建议吗?谢谢你。
EditText 可绘制:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/custom_edittext_bg_drawable_corners"/>
<solid android:color="@color/colorPrimary"/>
<stroke android:color="@color/colorSecondary" android:width="@dimen/custom_edittext_bg_border_width"/>
</shape>
按钮可绘制:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/custom_edittext_bg_drawable_corners"/>
<solid android:color="@color/colorSecondary"/>
<stroke android:color="@color/colorAccent" android:width="@dimen/custom_edittext_bg_border_width"/>
</shape>
解决方案
支持 MaterialButton 的所有属性。不要使用 android:background 属性。MaterialButton 管理自己的背景可绘制对象,设置新的背景意味着 MaterialButton 不能再保证它引入的新属性能够正常工作。如果更改了默认背景,则 MaterialButton 无法保证良好定义的行为。
所以我会做的是,我只需将 MaterialButton 更改为 Button 或 AppCompatButton
编辑
看来如果您有适当版本的金属组件(1.2.0-alpha06 或更高版本),您可以使用android:background
这里写的属性: