Android ListView Item Background Color
I am trying to allow the user to select more than one item. I want to "hig开发者_开发百科hlight" each list item selected so you can tell which item(s) have been selected.
I have tried:
view.setBackgroundResource();
view.setBackgroundColor();
view.setBackgroundDrawable();
I havent had any success.
Thannks for the help!
You need to use a custom array adapter , if you are using a listview with only one element you MAY be able to get away with some implemented listview method, but you will have much more flexibility and less headache if you make a custom array adapter instead. You can access all elements in it, each element can have its own onClickListener and everything
If you are passing a String array to the adapter,you can create custom adapter like this and can change background color of a selected item as below:
set the adapter to listview like:
String[] options={"abc","def","ghi","jkl"};
CustomAdapter ca=new CustomAdapter(this,options);
listView.setAdapter(ca);
and here is the custom adapter class:
public class CustomAdapter extends BaseAdapter
{
String items[];
LayoutInflater mInflater;
Context context;
public CustomAdapter(Context context,String[] items)
{
this.items=items;
this.context=context;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.cutsom_listitem, null);
holder = new ViewHolder();
holder.itemName=(TextView)convertView.findViewById(R.id.itemName);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
String option=items[position];
holder.itemName.setText(option);
holder.itemName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
holder.itemName.setBackgroundColor(Color.parseColor("#FF0000")); // making selected item red colored
}
});
return convertView;
}
@Override
public int getCount() {
return items.length;
}
@Override
public Object getItem(int position) {
return items[position];
}
@Override
public long getItemId(int position) {
return position;
}
}
public static class ViewHolder
{
TextView itemName;
}
u can overwrite setOnTouchListener in your adapter:
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
//the bacground when u select item
v.setBackgroundResource(android.R.color.holo_blue_light);
break;
case MotionEvent.ACTION_UP:
//设置背景为未选中正常状态
v.setBackgroundResource(android.R.color.background_light);
break;
default:
v.setBackgroundResource(R.drawable.mm_listitem_simple);
break;
}
return false;
}
you can set diffrence background when your action hanppend.
精彩评论