5

我如何設置,當用戶在列表視圖中選擇一個元素的動畫?的Android的ListView選擇動畫

:我將我自己的ListView適配器設置,即使一個粉紅色的背景和奇數行用紫色背景行。唯一的問題是我不知道如何爲用戶單擊(「觸摸」)元素設置動畫。

我想選擇時實施OnTouchListener更改背景爲綠色,但我遇到的問題可能是由於不再工作OnTouchListener正在實施的行內的按鈕。這是真的?

代碼:

public class MyAdapter extends BaseAdapter { 

    public View getView(int position, View convertView, ViewGroup parent) { 
     // position is the element's id to use 
     // convertView is either null -> create a new view for this element! 
     //    or not null -> re-use this given view for element! 
     // parent is the listview all the elements are in  

     if (convertView == null) { 
      convertView = mInflater.inflate(R.layout.your_layout, null); 

      // here you must do whatever is needed to populate the elements of your 
      // list element layout 
      ... 
     } else { 
      // re-use the given convert view 

      // here you must set all the elements to the required values 
     } 

     // your drawable here for this element 
     convertView.setBackground(...); 

     // maybe here's more to do with the view 
     return convertView; 
    } 
} 

回答

2

使用StateListDrawable與定義的項目爲state_selected。

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_selected="true" android:drawable="@drawable/selected" /> 
    ...Other States... 
    <item android:drawable="@drawable/normal" /> 
</selector> 

這樣,當選擇列表項時,它將自動使用該「選定」圖形。