如何给android中自定义列表视图的列表项提供两种不同的颜色?

时间:2014-06-02 09:17:23

标签: android listview background-color

有谁能告诉我如何给android中自定义列表视图的列表项提供两种不同的颜色? 如下图所示。是否可能?

enter image description here

建议

感谢您宝贵的时间!..

3 个答案:

答案 0 :(得分:1)

此代码可以帮助您,

将此代码插入自定义列表适配器

public class ListAdapter extends BaseAdapter{
    Context ctx;
    LayoutInflater lInflater;
    List<String> data;

    ListAdapter(Context context, List<String> data) {
        ctx = context;
        this.data = data;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.listitem, parent, false);
        }
// The logic is added here

        if (position % 2 == 0) {
            view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
        } else {
            view.setBackgroundResource(R.drawable.artists_list_background_alternate);
        }

        ((TextView) view.findViewById(R.id.yourText)).setText(data.get(position));

        return view;
    }
}

答案 1 :(得分:0)

在适配器(BaseAdapter)中使用它:

@Override
    public View getView(final int position, View v, ViewGroup parent) {


            LayoutInflater inflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.layout, null);
            if (position % 2 == 0) {
                yourView.setBackground("First Color ");
            } else {
                yourView.setBackground("second Color ");
            }

        return v;
    }

答案 2 :(得分:0)

只需检查getView()自定义列表适配器的方法就可以使用以下代码:

    @Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View v = convertView;

    ViewHolder holder = new ViewHolder();

    if (v == null) {
        Logger.show(Log.INFO, TAG, " getview v = null");

        LayoutInflater vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.categories_list_item, null);

        if (position % 2 == 0) {
            v.setBackground(getResources().getColor(R.color.red_color));
            // Declare red_color in color.xml as: <color name="red_color">#DF0101</color>
        } else {
            v.setBackground(getResources().getColor(R.color.blue_color));
            // Declare blue_color in color.xml as: <color name="blue_color">#FFFFFF</color>
        }


    } else {
        holder = (ViewHolder) v.getTag();
    }

    return v;
}