【親測有效】ListView中item點擊後變色(原來是透明的,點下變橙色擡手以後仍是橙色)

先在drawable裏寫個 item_selector_bg.xmljava

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="
//這裏是設置按下不鬆手時候的顏色,也能夠單純用顏色 @android:color/xxx 
//在colors裏設置例如 <color name="transparent">#00000000</color> 這樣
<item android:state_pressed="true" android:drawable="@drawable/list_item_p" />
<item android:drawable="@android:color/transparent"/>//默認時候顏色
</selector>

而後在layout裏把item佈局background設爲這個item_selector_bg.xmlandroid

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"
    android:background="@drawable/item_selector_bg"  
    android:orientation="horizontal"  
    >

然在baseadapter中的getview()方法裏ide

convertView.setTag(position);  
   convertView.setOnClickListener(new View.OnClickListener() {  
         
       @Override  
       public void onClick(View v) {  
           // TODO Auto-generated method stub  
           if(oldView == null){  
               //第一次點擊   
               oldView = v;  
               v.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.list_item_p));  
           }else{  
               //非第一次點擊   
               //把上一次點擊的 變化  
               oldView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.item_selector_bg));                     
           v.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.list_item_p));       
               //保存oldView          
             oldView = v;  
           }  
             
       }  
   });
//這一段是狀態保存
if(oldView != null && (position == (Integer)oldView.getTag())){// 爲點擊 item  
       convertView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.list_item_p));  
   }else{  
      convertView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.item_selector_bg));      
    }

後來我發現由於我寫的是VideoView,這個思路不適用,VideoView應該是根據當前播放什麼,而使相應的item變色
佈局

相關文章
相關標籤/搜索