2011-03-16 124 views
0

我試圖在點擊按鈕時更改按鈕的背景,但也可以在再次單擊時將其更改回來。我想要做的是獲取當前背景的按鈕,如果它是(xxxxx),則將其更改爲(yyyyy)。我似乎無法找到如何獲得按鈕的當前背景,並將其與我的可繪製資源之一進行比較。
任何幫助將不勝感激。根據當前背景更改按鈕的背景

的我想要做一些僞代碼:

if (button1.getBackground() == R.drawable.someDrawable) { 
    button1.setBackgroundResource(R.drawable.someOtherDrawable); 
} 

回答

3

我認爲這是正確的方式:link

+0

感謝Pedro,是我在創建項目時聲明的「包」包?這是它在你發佈的鏈接中說的... 在XML中:@ [package:] drawable/filename – billy 2011-03-16 21:49:26

+0

這是我自己的簡單選擇器:<?xml version =「1.0」encoding =「utf-8」?> <選擇器xmlns:android =「http://schemas.android.com/apk/res/android」> <! - pressed - > \t \t \t \t <! - default - > – pedr0 2011-03-17 10:17:46

1

我簡單的解決方法是將有兩個可繪製背景。一個用於non_pressed_selector和pressed pressed的壓縮選擇器,只要按下按鈕就可以跟蹤。

private boolean isPressed = false; 
public void onClick() { 
    if (isPressed) { 
     // set not_pressed_selector 
    } else { 
     // set pressed_selector 
    } 
    isPressed != isPressed; 
} 
0

看來你需要一個ToggleButton,而不是簡單的Button。您可以使用isChecked()方法確定OnClickListener中按鈕的狀態並在此處設置您的背景。或者你可以在xml中定義選擇器,就像p​​edr0說的那樣。

0

我所做的是:

聲明按鈕,在它的初始狀態:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/StateA"/> 
</selector> 

然後我管理從代碼controling按鈕的實際狀態與標籤的事件:

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.drawables_buttons); //This is the layout where it's the button 

    threeStateButton = (Button)findViewById(R.id.three_States_Button); //This is the button 
    threeStateButton.setOnTouchListener(new CustomTouchListener());  
    threeStateButton.setTag("StateA"); //Set the control tag 
} 

private class CustomTouchListener implements View.OnTouchListener 
{ 

    @Override 
    public boolean onTouch(View view, MotionEvent motionEvent) 
    { 
     switch (motionEvent.getAction()) 
     { 
      case MotionEvent.ACTION_UP: //When you lift your finger 
       if (threeStateButton.getTag().equals("StateA")) 
       { 
        threeStateButton.setBackgroundResource(R.drawable.StateB); 
        Toast.makeText(view.getContext(), "This gonna change my state from StateA to StateB",Toast.LENGTH_SHORT).show(); 
        threeStateButton.setTag("StateB"); 
       } 
       else //If when you lift your finger it was already on stateB 
       { 
        threeStateButton.setBackgroundResource(R.drawable.red_button); 
        Toast.makeText(view.getContext(), "This gonna change my state from StateB to StateA",Toast.LENGTH_SHORT).show(); 
        threeStateButton.setTag("StateA"); 
       } 
       break; 
      //In case you want that you button shows a different state when your finger is pressing it. 
      case MotionEvent.ACTION_DOWN: 
       threeStateButton.setBackgroundResource(R.drawable.StateButtonPressed); 
       break; 
     } 

     return false; 
    } 
} 

我不知道這是否是最好的辦法,但它的工作原理,是的,我想知道這是最佳的方式。