简体   繁体   English

带有复选框的列表视图中的Viewholder问题

[英]Problems with viewholder in a listview with checkbox

i'm trying to implement a listview with a checkbox. 我正在尝试实现带有复选框的列表视图。 the listener works well, i can see which item is selected buti have a problem in this class because cb.getTag() returns null. 侦听器运行良好,我可以看到选择了哪个项目,但是此类中有问题,因为cb.getTag()返回null。

private class MyCustomAdapter extends ArrayAdapter<TemaRescatado> {

    private class ViewHolder {
       TextView tema;
       CheckBox checkTema;
    }

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

        ViewHolder holder = null;

        if (convertView == null) {
           LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
           convertView = vi.inflate(R.layout.item_gen, null);

           holder = new ViewHolder();
           holder.tema = (TextView) convertView.findViewById(R.id.subtema);
           holder.checkTema = (CheckBox) convertView.findViewById(R.id.checktema);
           convertView.setTag(holder);

           holder.checkTema.setOnClickListener( new View.OnClickListener() { 
               public void onClick(View v) { 
                   CheckBox cb = (CheckBox) v ; 
                   TemaRescatado temaGen = (TemaRescatado) cb.getTag(); //returns null
                   temaGen.setSelected(cb.isChecked());
                    } 
           }); 
       }
       else {
        holder = (ViewHolder) convertView.getTag();
       }

       TemaRescatado temaGen = temaList.get(position);

       holder.tema.setText(temaGen.getTema());
       holder.checkTema.setChecked(temaGen.isSelected());
       holder.tema.setTag(temaGen);

       return convertView;

      }

     }

can anyone help me? 谁能帮我?

You have set a tag for your convertView which contains the CheckBox and for the tema TextView, but not for the CheckBox itself. 您已经为convertView设置了一个标签,其中包含CheckBox和tema TextView的tema ,但是没有为CheckBox本身设置。 Thus trying to get the tag for that CheckBox correctly returns null. 因此,尝试获取该CheckBox的标签正确返回null。

From looking through your code, it looks like what you really want to do is change 通过查看代码,您真正想要做的就是改变

holder.tema.setTag(temaGen);

to

holder.checkTema.setTag(temaGen);

This will give your CheckBox the temaGen tag instead of the TextView that is currently getting that tag. 这将为您的CheckBox提供temaGen标签,而不是当前正在获取该标签的TextView。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM