2011-03-23 65 views

回答

37

您想使用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」。

值/ 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> 
+0

小幅盤整風格= 「@風格/ MyCoolButton」 – user2582651 2017-03-04 06:28:28

8

導入PorterDuff和使用setColorFilter()如下

import android.graphics.PorterDuff.Mode; 

Button btn = (Button) findViewById(R.id.myButton); 
btn.getBackground().setColorFilter(Color.GRAY, Mode.MULTIPLY); 
= 「@風格/ CoolButton」 應改爲風格
+0

這將是如果您留下解釋而不僅僅是代碼,對讀者有幫助。 – 2017-04-13 00:56:22