appcompat-v7 自定义按钮颜色

appcompat-v7 custom button colors

是否可以为 appcompat-v7 自定义按钮颜色?默认按钮是灰色的,我想在整个应用程序中将它们更改为绿色。将 android:background 设置为可绘制对象会移除弯曲的边缘。

为此,您需要在您的应用中创建自定义布局。在您的可绘制文件夹中创建一个 xml 文件,命名为 custom_button.xml。

添加以下代码:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <stroke
                android:width="0dp"
                android:color="#000000" />
            <solid
                android:color="ColourCode of the colour you Want to give"
                />
            <corners
                android:radius="0dp"
                android:bottomLeftRadius="0dp"
                android:bottomRightRadius="0dp"
                android:topLeftRadius="0dp"
                android:topRightRadius="0dp"/>
        </shape>
    </item>
</selector>

保存 xml 文件,然后在定义按钮的 activity_main.xml 文件中,添加 custom_button 作为背景。

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/titleButton"
    android:background="@drawable/custom_button"/>

现在可以使用了

像这样在您的可绘制目录中创建一个名为 "shape_btn.xml" 的新文件,将 android:color 更改为您喜欢的内容:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="@dimen/abc_button_inset_horizontal_material"
       android:insetTop="@dimen/abc_button_inset_vertical_material"
       android:insetRight="@dimen/abc_button_inset_horizontal_material"
       android:insetBottom="@dimen/abc_button_inset_vertical_material">
    <shape android:shape="rectangle">
        <corners android:radius="@dimen/abc_control_corner_material" />
        <solid android:color="@android:color/black" />
        <padding android:left="@dimen/abc_button_padding_horizontal_material"
                 android:top="@dimen/abc_button_padding_vertical_material"
                 android:right="@dimen/abc_button_padding_horizontal_material"
                 android:bottom="@dimen/abc_button_padding_vertical_material" />
    </shape>
</inset>

并设置为按钮背景:

<Button
    ...
    android:background="@drawable/shape_btn"
    />

如果您想将它应用到您应用中的所有按钮,请像这样更改您的主题背景:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:buttonStyle">@style/MyButtonStyle</item>
</style>

<style name="MyButtonStyle" parent="Widget.AppCompat.Button" >
    <item name="android:background">@drawable/shape_btn</item>
</style>

由于您明确询问如何使用 appcompat-v7 - 这是推荐的方法。
首先:不需要创建新的可绘制对象。您可以使用具有 colorButtonNormal 属性的主题来简单地更改按钮的颜色。

下面举例:

styles.xml

<style name="ThemeButton">
        <item name="colorButtonNormal">#009688</item>
</style>

layout.xml

<!-- other layout elements -->

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="My Button"
    android:textColor="@android:color/white"
    android:theme="@style/ThemeButton" />

结果:

这样您将在按下按钮时保持标准的高度和波纹效果,而使用自定义可绘制对象时则不是这种情况。 (至少如果你不使用选择器)