2011年7月1日 星期五

Android改變按鈕顏色

    最近在研究Android 的UI想到需要改變按鈕的顏色,讓UI更漂亮 or 讓使用者知道目前所選擇的項目,Google了一下,有幾種方法,整理讓有需要的人,參考參考!


1. setBackgroundColor
原本的按鈕型式改變了,旁邊的圓弧形不見了,變成了直角,看起跟其它按鈕格格不入。
Button1.setBackgroundColor(Color.GREEN)

2. xml來客製button
利用在xml中設定shape的圖形來畫button,彈性大,可做漸層等效果。
必須先製作一個描述 shape xml
 

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>       
        <shape>
            <gradient
                android:id="@+id/shape"
                android:startColor="#ff0000"
                android:endColor="#ffff00"
                android:angle="270" />
            <corners
                android:radius="10dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
 
然後把Background設成該xml即可
 
Button2.setBackgroundResource(R.layout.button);
 

3. 改變 buttonbackground filter
改變backgound filter來改變顏色,簡單!

Button4.getBackground().setColorFilter(
   0xFF00FF00, 
   android.graphics.PorterDuff.Mode.MULTIPLY );


沒有留言:

張貼留言