2014-04-03 95 views
0

所以我用3個按鈕製作應用程序。目前我有以下的.xml文件,使他們有四捨五入的邊緣和紅色的顏色。現在我想讓它們如此,如果選擇了一個,那麼該按鈕會變成綠色,而另外兩個保持不變,或者變回紅色。我怎麼能這樣做呢?我必須製作另一個.xml文件嗎? 下面是我的按鈕繪製.xml文件:選擇一個按鈕時更改按鈕的顏色; Android開發

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" android:padding="10dp"> 
    <!--red colour.--> 
    <solid android:color="#FF0000"/> 
    <corners 
     android:bottomRightRadius="10dp" 
     android:bottomLeftRadius="10dp" 
     android:topLeftRadius="10dp" 
     android:topRightRadius="10dp"/> 
    <stroke android:width="2px" android:color="#000000"/> 
</shape> 
+0

是的,你需要寫不同的可繪製的不同的固體和筆畫顏色。 –

+1

我會用3 RadioButtons RadioGrop,而不是**保持按下狀態**(按鈕狀態是瞬間的)。您可以刪除按鈕圖形,並使用紅/綠狀態的自定義選擇器作爲背景 –

回答

2

使用selector如下:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <!-- green state --> 
    <item 
     android:drawable="@drawable/button_selected" 
     android:state_selected="true"></item> 
    <!-- green state --> 
    <item 
     android:drawable="@drawable/button_pressed" 
     android:state_pressed="true"></item> 
    <!-- red state --> 
    <item 
     android:drawable="@drawable/button_disabled"></item> 

</selector> 

然後,你應該把這種選擇,如:

<Button 
    ... 
    android:background="@drawable/my_selector" /> 

,創造每個drawable.xml(作爲紅色按鈕的示例):button_selected,button_pressed and button_disabled

您還可以通過使用onTouchListener等殘留狀態:

button.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
       // change the color 
       return true; 
      case MotionEvent.ACTION_UP: 
       // intitial color 
       return true; 
      default: 
       return false; 
     } 
    } 
}); 

然而,最好使用Selectorbackground,這種使用較少的資源。


UPDATE:

可以使用setBackgroundResource方法來保持和改變點擊按鈕的背景狀態如下:

// 1st clicklistener method 
button.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     v.setBackgroundResource(R.drawable.green_drawable); 
     button2.setBackgroundResource(R.drawable.selector_drawable); 
    } 
} 

// 2nd clicklistener method 
button2.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     v.setBackgroundResource(R.drawable.green_drawable); 
     button1.setBackgroundResource(R.drawable.selector_drawable); 
    } 
} 

未經測試,但它應該工作。

+0

Hi @ theGuy05,它不起作用,這不是您要查找的內容嗎? – Fllo

+0

好的,非常感謝!現在他們會成爲一種讓按鈕在點擊後保持綠色的方式嗎?那麼當另一個按鈕被點擊時,該按鈕會變成綠色?像單選按鈕,但不使用單選按鈕。 – theGuy05

+0

@ theGuy05我更新了我的答案,我沒有測試這個,但這應該可以做到。讓我知道它是否工作。 HTH – Fllo