圆角+背景颜色Android按钮的动态设置?

问题描述 投票:8回答:2

我想在我的应用程序中为Button提供以下设置。您可以将其视为按钮的某些主题更改。

Style舍入或普通

颜色红色或黄色或蓝色或任何颜色代码

我知道使用XML定义的Shape,可以实现圆角。使用setBackgroundColor,我可以将任何颜色设置为背景。

问题

setBackgroundColorsetBackground都基于我称呼它们的顺序互相覆盖。因此,我无法在同一按钮上同时实现这两种效果。如何同时实现这两种效果。如何从单个Button类获得多个按钮的下方。在此先感谢。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS84WXBiYy5wbmcifQ==” alt =“在此处输入图像描述”>

android android-button android-theme android-styles
2个回答
8
投票

我用GradientDrawable做到了

    int color = Color.rgb(255,0,0); //red for example
    int radius = 5; //radius will be 5px
    int strokeWidth = 2;

    GradientDrawable gradientDrawable = new GradientDrawable();
    gradientDrawable.setColor(color);
    gradientDrawable.setCornerRadius(radius);
    gradientDrawable.setStroke(strokeWidth, color);
    button.setBackground(gradientDrawable);

7
投票

您可以在可绘制资源中设置按钮的形状和背景颜色,并将其分配为XML中的android:background或代码中的setBackgroundDrawable()

以下是此类按钮的示例:

/ res / drawable / button.xml此文件用于设置圆形和背景颜色

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <solid android:color="#ffffff" />
            <corners android:radius="16dp" />
            <stroke
                android:width="3dp"
                android:color="#ff0000" />
        </shape>
    </item>

    <item android:state_selected="true">
        <shape android:shape="rectangle">
            <solid android:color="#ffffff" />
            <corners android:radius="16dp" />
            <stroke
                android:width="3dp"
                android:color="#ff0000" />
        </shape>
    </item>

    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#ff0000" />
            <corners android:radius="16dp" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle">
        <solid android:color="#ffffff" />
        <corners android:radius="16dp" />
        <stroke
            android:width="3dp"
            android:color="#0000ff" />
    </shape>
    </item>

</selector>

/ res / color / button.xml(此文件用于设置文本颜色)

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:color="#0000ff" />
    <item android:state_focused="true" android:color="#0000ff" />
    <item android:state_selected="true" android:color="#0000ff" />
    <item android:color="#000000" />

</selector>

然后您可以将布局中的按钮初始化为:

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/button"
    android:background="@drawable/button"/>

该按钮的外观如下(默认和从上到下的按下状态:]

“在此处输入图像说明”“ >>


0
投票

仅作为背景的梯度

© www.soinside.com 2019 - 2024. All rights reserved.