10

我需要在android中做背景颜色变化的圆角按钮。

我怎么能这样做?

示例链接/代码非常感谢。

4

2 回答 2

39

您想使用 Android 的 Shape Drawables。 http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

可绘制/cool_button_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="@dimen/corner_radius" />
    <gradient
        android:angle="270"
        android:startColor="@color/almost_white"
        android:endColor="@color/somewhat_gray"
        android:type="linear" />
</shape>

然后,您必须从这些形状可绘制对象中创建一个“选择器”可绘制对象。这允许您根据状态使按钮显示不同。IE:按下、聚焦等 http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

可绘制/cool_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/cool_inner_press_bottom" />
    <item android:state_focused="true" android:state_enabled="true"
        android:state_window_focused="true"
        android:drawable="@drawable/cool_inner_focus_bottom" />
    <item
         android:drawable="@drawable/cool_button_background" />
</selector>

奖励:您可能希望为按钮创建一种样式,以便使它们在整个程序中保持一致。您可以省略这一步,只需设置按钮的 android:background="@drawable/cool_button"。

值/样式.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCoolButton">
        <item name="android:background">@drawable/cool_button_background</item>
    </style>
</resources>

最后,按钮!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/appwidget_bg">
    <Button
        android:id="@+id/btnAction"
        android:layout_width="wrap_content"
        android:layout_weight="wrap_content"
        style="@style/CoolButton"
        />
</LinearLayout>
于 2011-03-23T05:46:45.760 回答
8

导入 PorterDuff 并使用 setColorFilter() 如下

import android.graphics.PorterDuff.Mode;

Button btn = (Button) findViewById(R.id.myButton); 
btn.getBackground().setColorFilter(Color.GRAY, Mode.MULTIPLY);
于 2011-04-01T17:53:35.487 回答