Sam*_*hen 23 android android-button android-drawable android-styles material-design
我发现从 Android Studio 4.1 开始,我无法Button通过在 a 上设置颜色来更改 a 的背景颜色android:background,只是没有效果。自定义Drawable也不起作用。
我的背景Drawable:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1.5dp"
android:color="@android:color/black" />
<solid
android:color="@android:color/white" />
<corners
android:radius="8dp" />
</shape>
Run Code Online (Sandbox Code Playgroud)
我的Button:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add To Cart"
android:background="@drawable/background3"/>
Run Code Online (Sandbox Code Playgroud)
结果:
Com*_*are 50
Android Studio 4.1 新项目向导,对于它的许多模板,项目都使用 Material Components for Android 库。并且,它将默认主题设置为基于Theme.MaterialComponents.DayNight.DarkActionBar.
这样做的一个副作用是<Button>布局中的任何元素都会变成MaterialButton小部件,而不是常规Button小部件。MaterialButton忽略android:background.
如果您只想更改颜色,请使用android:backgroundTint或更改colorPrimary主题中的属性。
如果您想要一个具有自定义背景的按钮,并且您的主题设置为使用Theme.MaterialComponents,则可以将布局中的 XML 元素切换<android.widget.Button>为<Button>。这应该会导致 Android 的 Material 组件忽略该元素,并且您可以根据 XML 属性正常操作此按钮。
Sam*_*hen 26
更新 03/2021
app:backgroundTint="@null" //just need this
android:background="@drawable/background_button"
Run Code Online (Sandbox Code Playgroud)
好的,由于MaterialButton是Button从 Android Studio 4.1 开始的默认设置,我们可以通过使用app:shapeAppearanceOverlay属性来修改形状。
1. 在 中创建自定义样式themes.xml:
<style name="leaf">
<item name="cornerSizeTopLeft">70%</item> //can specify corner position
<!--<item name="cornerFamilyTopLeft">cut</item>-->
<item name="cornerSizeBottomRight">70%</item>
<!--<item name="cornerFamilyBottomRight">cut</item>-->
</style>
Run Code Online (Sandbox Code Playgroud)
2. 应用样式Material Button:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Show"
app:shapeAppearanceOverlay="@style/leaf" /> //here
Run Code Online (Sandbox Code Playgroud)
结果:
小智 5
通过设置app:backgroundTint="@null"
你的材质按钮将不再是圆形的。要使其变圆并设置线性渐变颜色等,请将其添加到可绘制文件中:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<stroke
android:width="2dp"
android:color="@color/lightBlue" />
<corners android:radius="8dp"/>
<gradient android:endColor="#FFD374" android:startColor="#FFBC68" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<stroke
android:width="2dp"
android:color="@color/lightBlue" />
<corners android:radius="8dp"/>
<gradient android:endColor="#FFBC68" android:startColor="#FFD374" />
</shape>
</item>
</selector>
Run Code Online (Sandbox Code Playgroud)
转到 xml 文件并像这样添加它
<com.google.android.material.button.MaterialButton
...........
app:backgroundTint="@null"
android:background="@drawable/linear_gradient"
..........
/>
Run Code Online (Sandbox Code Playgroud)
注意:根据您的需要进行编辑...
| 归档时间: |
|
| 查看次数: |
12374 次 |
| 最近记录: |