Drawable不适用于我的按钮格式

时间:2019-11-03 18:26:34

标签: android drawable android-button material-components material-components-android

我有这个Drawable用来做我的圆形按钮:

from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('Jan-09'), '%b-%y')
date2 = datetime.strptime(str('Jan-18'), '%b-%y')
r = relativedelta.relativedelta(date2, date1)

total_months = r.years*12 + r.months

print("Total months: {0}".format(total_months))

我通常在按钮的背景下给他打电话...

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary"/>
            <corners android:radius="150dp"/>
        </shape>
    </item>
</selector>

但是没有对组件进行任何更改,我尝试在其他组件上使用Drawable,但它不适用...我不知道为什么会发生这种情况。

我的完整屏幕:

<Button
        android:id="@+id/btnPhoto"
        android:background="@drawable/bg_btn_rounded"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="42dp"
        android:layout_marginEnd="8dp"
        android:text="@string/btnphoto"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

2 个答案:

答案 0 :(得分:1)

您是否使用“材料组件”主题?如果是这样,您的<Button>标签将被夸大为com.google.android.material.button.MaterialButtonThe documentation的此小部件状态:

  

请勿使用android:background属性。 MaterialButton管理其自己的背景可绘制对象,并且设置新的背景意味着MaterialButton不再能够保证其引入的新属性将正常运行。

如果不想特殊的MaterialButton行为,则可以显式指定要使用的其他按钮类。改为将您的<Button>标记改为:

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/btnPhoto"
    android:background="@drawable/bg_btn_rounded"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="42dp"
    android:layout_marginEnd="8dp"
    android:text="@string/btnphoto"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" /

答案 1 :(得分:1)

如果您使用的是Material Theme,则启用了自动充气,它将在运行时将<Button>替换为<com.google.android.material.button.MaterialButton>
还要检查此question

只需使用 app:backgroundTint 外观定义背景颜色,并使用 app:cornerRadius 定义拐角半径。

类似的东西:

<com.google.android.material.button.MaterialButton
    android:id="@+id/btnPhoto"
    app:backgroundTint="@color/primaryLightColor"
    app:cornerRadius="150dp"
    android:layout_width="150dp"
    android:layout_height="150dp"/>

enter image description here