Android ListView项目背景颜色

时间:2011-10-17 03:07:08

标签: android listview background-color

我试图让用户选择多个项目。我想“突出显示”所选的每个列表项,以便您可以判断选择了哪个项目。

我试过了: view.setBackgroundResource(); view.setBackgroundColor(); view.setBackgroundDrawable();

我没有取得任何成功。

谢谢你的帮助!

3 个答案:

答案 0 :(得分:0)

您需要使用自定义数组适配器,如果您使用的listview只有一个元素,您可以使用一些实现的listview方法,但如果您进行自定义,您将获得更大的灵活性和更少的头痛而是数组适配器。您可以访问其中的所有元素,每个元素都可以拥有自己的onClickListener和所有内容

答案 1 :(得分:0)

如果要将String数组传递给适配器,可以像这样创建自定义适配器,并可以更改所选项目的背景颜色,如下所示:

将适配器设置为listview,如:

String[] options={"abc","def","ghi","jkl"};

CustomAdapter ca=new CustomAdapter(this,options);    
listView.setAdapter(ca);

这是自定义适配器类:

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;
}

答案 2 :(得分:0)

你可以覆盖适配器中的setOnTouchListener:

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;
        }

你可以在你的行动发生时设置差异背景。

相关问题