2015-05-21 25 views
2

我製作了android和arduino應用程序來控制我的站立桌。我上傳的GitHub上(https://github.com/neosarchizo/MyStandingDesk)這個項目按下狀態的android選擇器不起作用

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

我想在MainActivity按鈕使用選擇。如果我按下某個按鈕,則必須更改該按鈕的圖像。但它沒有奏效。所以我通過檢查MotionEvent以編程方式更改按鈕的圖像。

btnDown.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View view, MotionEvent motionEvent) { 

       switch (motionEvent.getAction()) { 
        case MotionEvent.ACTION_DOWN: 
         btnDown.setImageResource(R.drawable.down_button_pressed); 
         sendCommand("a"); 
         break; 
        case MotionEvent.ACTION_UP: 
         btnDown.setImageResource(R.drawable.down_button); 
         sendCommand("s"); 
         break; 
       } 
       return true; 
      } 
     }); 

此外,我在佈局xml文件中爲選擇器編寫了以下代碼。

<ImageButton 
    android:id="@+id/btnDown" 
    android:layout_width="fill_parent" 
    android:layout_height="0px" 
    android:layout_margin="30dip" 
    android:layout_weight="1" 
    android:scaleType="fitCenter" 
    android:background="@android:color/transparent" 
    android:src="@drawable/selector_down_button" /> 

回答

3

更改此

android:src="@drawable/selector_down_button" 

android:background="@drawable/selector_down_button" 

您可能希望在獲取ACTION_DOWN事件時啓用「按下」狀態,並在獲取ACTION_UP事件時將其禁用。

btnDown.setOnTouchListener(new View.OnTouchListener() { 
       @Override 
       public boolean onTouch(View view, MotionEvent motionEvent) { 

        switch (motionEvent.getAction()) { 
         case MotionEvent.ACTION_DOWN: 
          btnDown.setImageResource(R.drawable.down_button_pressed); 
          sendCommand("a"); 
          view.setPressed(true); 
          break; 
         case MotionEvent.ACTION_UP: 
          btnDown.setImageResource(R.drawable.down_button); 
          sendCommand("s"); 
          view.setPressed(false); 
          break; 
        } 
        return true; 
       } 
      }); 
+0

我已經試過了。但它也沒有工作。請克隆我的項目並進行測試。 – neosarchizo

+0

現在檢查我更新的答案我已經測試it.it的工作完美。 –

+0

我可以解決這個問題沒有'view.setPressed()'? – neosarchizo

2

剛剛嘗試這一點

android:background="@drawable/selector_down_button" 

將選擇作爲background