Question

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.

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?

Was it helpful?

Solution

You have set a tag for your convertView which contains the CheckBox and for the tema TextView, but not for the CheckBox itself. Thus trying to get the tag for that CheckBox correctly returns 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top