我需要在Android中实现带有背景颜色变化的圆角按钮。
我该如何做到这一点?
例子的链接/代码将非常感激。
<?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>
然后,您需要从这些形状可绘制对象中创建一个“选择器”可绘制对象。这样可以使按钮在不同的状态下显示不同的外观,例如:按下、聚焦等。 http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
drawable/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"。
values/styles.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>
导入PorterDuff并按以下方式使用setColorFilter()
import android.graphics.PorterDuff.Mode;
Button btn = (Button) findViewById(R.id.myButton);
btn.getBackground().setColorFilter(Color.GRAY, Mode.MULTIPLY);