listview - 访问项目点击时的viewHolder元素

时间:2016-01-21 19:40:47

标签: android listview

我有一个带有viewHolder的customAdapter,其中包含一个customView(圆形) 我需要检索视图持有者中包含的视图的颜色,而不是对象项

我该怎么做? 非常感谢你

我的适配器:

public class WelcomeAdapter extends BaseAdapter {

// contex
private Context context;

// Liste a affichée
private RealmList<Measure> welcomeList;

public RealmList<WelcomeList> getWelcomeList() {
    return welcomeList;
}

private LayoutInflater inflater = null;

private int color1;
private int color2;
private int color3;



public WelcomeAdapter (Context context, RealmList<Welcome> welcomeList) {
    this.context = context;
    this.welcomeList= welcomeList;

    color1= ContextCompat.getColor(context, R.color.green);
    color2= ContextCompat.getColor(context, R.color.yellow);
    color3= ContextCompat.getColor(context, R.color.blue);


    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return welcomeList== null ? 0 : welcomeList.size();
}

@Override
public Object getItem(int position) {
    return welcomeList== null ? null : welcomeList.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.row_welcome, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.cs = (CircleShape) convertView.findViewById(R.id.row_welcome_cv);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    Welcome welcome= WelcomeList.get(position);



    if (welcome.getWelcomePeople() != null) {
        for (People p : welcome.getWelcomePeople()) {
            if (p.getNumber() > 5) {
                 viewHolder.cs.setColor(color1);
            } else if (p.getNumber() > 15) {
                 viewHolder.cs.setColor(color2);
            } else if (p.getNumber() > 25) {
                 viewHolder.cs.setColor(color3);
            }
        }
    }

    return convertView;
}

 class ViewHolder {
    CircleShape cs;

}

活动

protected AdapterView.OnItemClickListener welcomeClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // need to retrieve the current color of the CircleShape of the view holder associated with the item clicked there

        }
    };

非常感谢

1 个答案:

答案 0 :(得分:3)

如果我没有弄错,您应该能够通过在返回给您的视图上调用getTag()来检索视图持有者,因为您正在使用{{将标记设置为视图持有者1}}

因此,获取convertView.setTag(viewHolder)的{​​{1}}方法应如下所示:

onItemClick

如果可行,请告诉我,我对适配器有点生疏。