2013-04-15 150 views
0

在Android應用程序中,我想更改Button的背景顏色。按鈕的背景

我試圖將android:Drawable/btn_default_holo_light的「背景」屬性更改爲#FFFF00,並根據需要獲得了新顏色。缺點是Button的形狀也發生了變化:原來的Button的邊距消失了,彩色區域變得越來越大,完全填滿了它的區域。

如何更改背景顏色而不是Button的外觀?

回答

4

您可以設置按鈕背景使用自定義編程可繪

b= (Button) findViewById(R.id.button1); 
b.setBackgroundColor(Color.RED); 

設置背景。

buttonbkg.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/pressed" /> 
<item android:state_focused="false" 
    android:drawable="@drawable/normal" /> 
</selector> 

在繪製文件夾中的.xml正常

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FFFFFF"/>  
<stroke android:width="3dp" 
     android:color="#0FECFF" /><!-- #330000FF #ffffffff --> 
<gradient 
    android:startColor="#ffffffff" 
    android:endColor="#110000FF" 
    android:angle="90"/> 

<padding android:left="5dp" 
     android:top="5dp" 
     android:right="5dp" 
     android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp" 
     android:bottomLeftRadius="7dp" 
     android:topLeftRadius="7dp" 
     android:topRightRadius="7dp"/> 

</shape> 

pressed.xml

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FF1A47"/>  
<stroke android:width="3dp" 
     android:color="#0FECFF"/> 
<padding android:left="5dp" 
     android:top="5dp" 
     android:right="5dp" 
     android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp" 
     android:bottomLeftRadius="7dp" 
     android:topLeftRadius="7dp" 
     android:topRightRadius="7dp"/> 

在你activity_main.xml中

<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:background="@drawable/buttonbkg" or android:background="#0EFFFF" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_marginTop="20dp" 
    android:text="Click" /> 
+0

謝謝。我不認爲這個問題已經回答了所問的問題,但這些信息仍然有用! –

0

由於Button形狀是在其背景圖像中定義的,因此不能僅更改背景色。如果你想要一個不同的顏色,那麼你需要創建自己的背景。只是谷歌的「android自定義按鈕」,你會發現噸的信息和教程。

0

那麼按鈕標籤中只有android:backgroud=#FFFF00。我認爲這將保持可繪製的主題,因此保持利潤率,但改變顏色。或者這是你已經嘗試過的嗎?