Listview突出显示了多项选择的项目

时间:2015-09-15 19:49:30

标签: android listview android-listview android-listfragment android-adapterview

我已经从listview中为突出显示的项目编写了代码,我点击了它,但它一次仅适用于1个项目。我想突出显示多个项目。

public class myadapter extends ArrayAdapter<ItemList> {
    private Context context;
    private ArrayList<ItemList> values;

    private int selectedIndex;
    private int selectedColor = Color.parseColor("#1b1b1b");

    public BrandselectedAdapter(Context context, ArrayList<ItemList> values) {
        super(context, R.layout.row_item, values);

        this.context = context;
        this.values = values;
        selectedIndex = -1;

    }

    public void setSelectedIndex(int ind) {
        selectedIndex = ind;
        notifyDataSetChanged();
    }

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

        if (v == null) {
            final LayoutInflater vi = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row_item, null);
            holder = new ViewHolder();
            holder.txt = (TextView) v.findViewById(R.id.name);

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

        ItemList mi = values.get(position);

        holder.txt.setText(mi.getName().toString());

        if (selectedIndex != -1 && position == selectedIndex) {
            holder.txt.setTextColor(Color.YELLOW);
        } else {
            holder.txt.setTextColor(Color.RED);
        }

        return v;
    }

    static class ViewHolder {
        public TextView txt;

    }
}

Listview点击事件:

itemlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        int wantedPosition = position; 
        int firstPosition = listbrand.getFirstVisiblePosition() - listbrand.getHeaderViewsCount(); // This is the same as child #0
        int wantedChild = wantedPosition - firstPosition;
        if (wantedChild < 0 || wantedChild >= listbrand.getChildCount()) {

            Toast.makeText(mContext, "Sorry", Toast.LENGTH_SHORT).show();
            return;
        }

        View wantedView = listbrand.getChildAt(wantedChild);

        myadapter.setSelectedIndex(position);


    }
});

从上面的代码我可以从listview更改所选项目的颜色,但它只适用于1项。

假设我有项目

a
b
c
d
e

当我点击a时,a的颜色将根据我的代码更改为RED。现在,当我选择b时,b的颜色将更改为根据我的代码,REDa的颜色也会更改为YELLOW

所以我希望当我点击任何项目然后它的颜色变成RED然后当我再次点击相同的项目然后只有项目颜色变成YELLOW

0 个答案:

没有答案