ListItem更改背景色

ListItem更改背景色,可能不是很好,但能达到效果,点击、长按、方向键选中都会保留背景色:
1、listView控件
       <ListView
android:id=”@+id/contact_listview”
android:layout_width=”wrap_content”
android:layout_height=”400dip”
android:divider=”#b9b9b9″
android:dividerHeight=”1px”
android:cacheColorHint=”#00000000″
android:listSelector=”@drawable/list_selector”
android:headerDividersEnabled=”true”>
</ListView>

2、在drawable文件夹中见一个list_selector.xml文件,不用写什么内容,只是用来把系统自带的给覆盖掉。
   < xml version=”1.0″ encoding=”UTF-8″ >
   <selector xmlns:android=”http://schemas.android.com/apk/res/android”>

   </selector>

3、在values文件夹中新建一个colors.xml文件,用来写颜色值:
< xml version=”1.0″ encoding=”utf-8″ >
<resources>
    <color name=”list_item_focus”>#626fcd</color>
</resources>

4、在java文件里定义一个私有变量private View itemView;用来保存上一次选中的listitem。

5、在下面三种事件中改变背景色
        //listview的itme选中事件
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView< > arg0, View arg1, int arg2,
long arg3) {
itemBackChanged(arg1);
position = arg2;
}
@Override
public void onNothingSelected(AdapterView< > arg0) {
}
};

        //长按事件
private OnItemLongClickListener itemLongClickListener = new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView< > parent, View view,
int position, long id) {
itemBackChanged(view);
ContactGrpMemActivity.this.position = position;
return false;
}
};

//listview的item点击事件
private OnItemClickListener itemClicklistener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView< > arg0, View arg1, int arg2,
long arg3) {
Log.i(TAG, “**************onItemClick arg0 is ” + arg0.getClass().getName());
Log.i(TAG, “**************onItemClick arg1 is ” + arg1.getId());
Log.i(TAG, “**************onItemClick arg2 is ” + arg2);
Log.i(TAG, “**************onItemClick arg3 is ” + arg3);
itemBackChanged(arg1);
position = arg2;
}
};

//改变listitem的背景色
private void itemBackChanged(View view) {
                //改变当前点击的listitem中textview的字体颜色
TextView contactName = (TextView)view.findViewById(R.id.contactName);
TextView contactTel = (TextView)view.findViewById(R.id.contactTel);
contactName.setTextColor(Color.WHITE);
contactTel.setTextColor(Color.WHITE);

if(itemView == null) itemView = view;
if(itemView != view) {
                       //改变上次点击点击的listitem中textview的字体颜色
contactName = (TextView)itemView.findViewById(R.id.contactName);
contactTel = (TextView)itemView.findViewById(R.id.contactTel);
contactName.setTextColor(Color.BLACK);
contactTel.setTextColor(Color.BLACK);
}

itemView.setBackgroundColor(android.R.color.transparent);//将上次点击的listitem的背景色设置成透明
view.setBackgroundResource(R.color.list_item_focus);//设置当前点击的listitem的背景色
itemView = view;
}

6、如果是图片的话,第三部可以跳过,第5步中view.setBackgroundResource(R.color.list_item_focus)改成view.setBackgroundResource(R.drawable.select_bar);就行了

发表评论

电子邮件地址不会被公开。 必填项已用*标注