1

I am trying to check the checkbox of my custom listView items.

I am trying by using view.setOnClickListener on my custom listview Adapter.

When I am selecting one item of the listView item, another item is also getting selected down of the list.

My getView code

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

    if (view == null){
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        view = inflater.inflate(row, parent, false);

        holder = new ViewHolder();

        holder.studentName = (TextView) view.findViewById(R.id.studentName);
        holder.id = (TextView) view.findViewById(R.id.studentID);
        holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox);
        view.setTag(holder.checkBox);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!holder.checkBox.isChecked() && view!=null) {
                    holder.checkBox.setChecked(true);
                    presentStudent.add(data.get(position));
                    Toast.makeText(context, "added " + data.get(position).getName(), Toast.LENGTH_SHORT).show();
                }
                else {
                    holder.checkBox.setChecked(false);
                    presentStudent.remove(data.get(position));
                    Toast.makeText(context, "removed " + data.get(position).getName(), Toast.LENGTH_SHORT).show();
                }



            }
        });

        view.setTag(holder);

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

    if((data == null) || ((position+1) > data.size()))
        return view;

    studentData = data.get(position);



    if ((holder.studentName != null) && null != studentData.getName()
            && studentData.getName().trim().length() > 0 )
        holder.studentName.setText(Html.fromHtml(studentData.getName()));

    if ((holder.id != null) && null != studentData.getAcademicId()
            && studentData.getAcademicId().trim().length() > 0 )
        holder.id.setText(Html.fromHtml(studentData.getAcademicId()));


    return view;
}

Here is my Layout code:

  <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <TextView
            android:layout_marginBottom="10dp"
            android:text="ID: 20151057010 (057)"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/studentID"
            android:layout_alignBottom="@+id/checkBox"
            android:layout_alignLeft="@+id/studentName"
            android:layout_alignStart="@+id/studentName" />

        <ImageView

            android:layout_width="40dp"
            android:layout_height="40dp"
            android:id="@+id/image"
            android:src="@drawable/student_icon"
            android:layout_marginLeft="14dp"
            android:layout_marginStart="14dp"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <CheckBox
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox"
            android:layout_below="@+id/studentName"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="11dp"
            android:layout_marginEnd="11dp" />

        <TextView
            android:id="@+id/studentName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sudarshan Mondal"
            android:textSize="20sp"
            android:layout_marginLeft="31dp"
            android:layout_marginStart="31dp"
            android:layout_alignTop="@+id/image"
            android:layout_toRightOf="@+id/image"
            android:layout_toEndOf="@+id/image"
            android:layout_marginTop="10dp"/>
    </RelativeLayout>


   </LinearLayout>

I have selected this item This item automatically get selected

What should I do?

2
  • I added my answer. Simply update your getview() method and you are good to go :) Commented Oct 6, 2016 at 4:58
  • Are you done with this? Commented Oct 6, 2016 at 8:22

4 Answers 4

2

It's happening because of default behaviour of listview to reuse inflated view. Take temporary arraylist to store clicked position and verify the same arraylist whether it is contained that specific position or not inside getView method. Declare arraylist inside your adapter class, Here you go :

ArrayList<String> selectedPosition = new ArrayList<String>();

Now update your getView() method as per below :

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

    if (view == null){
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        view = inflater.inflate(row, parent, false);

        holder = new ViewHolder();

        holder.studentName = (TextView) view.findViewById(R.id.studentName);
        holder.id = (TextView) view.findViewById(R.id.studentID);
        holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox);
        //view.setTag(holder.checkBox); No need to do this

        view.setTag(holder);

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

    if((data == null) || ((position+1) > data.size()))
        return view;

    studentData = data.get(position);



    if ((holder.studentName != null) && null != studentData.getName()
            && studentData.getName().trim().length() > 0 )
        holder.studentName.setText(Html.fromHtml(studentData.getName()));

    if ((holder.id != null) && null != studentData.getAcademicId()
            && studentData.getAcademicId().trim().length() > 0 )
        holder.id.setText(Html.fromHtml(studentData.getAcademicId()));

      //Added Change here...Check if arraylist contains selectedposition or not?

        if(selectedPosition.contains(String.valueOf(position))){
               holder.checkBox.setChecked(true);
               presentStudent.add(data.get(position));
        }else{
               holder.checkBox.setChecked(false);
               presentStudent.remove(data.get(position));
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


           //Simply store and check selectedPosition

           if(selectedPosition.contains(String.valueOf(position)))
               selectedPosition.remove(String.valueOf(position));
           else
               selectedPosition.add(String.valueOf(position));

           //And then update adapter
           notifyDataSetChanged();

            }
        });


    return view;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You have added setTag() twice, surely that is messing up. While doing setTag() for first time, you are setting tag for checkbox but while doing getTag() you are taking complete holder.

Edit:

It reuses your view while scrolling. You will have to implement checkedchangelistener for checkboxes and update the checkbox state:

 holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Maintain checkbox state here, which you need to check inside view.setOnClickListener..
            }
        });

Also post the 'row' layout if above didn't help.

2 Comments

I've removed view.setTag(holder.checkBox); and still facing that problem.
I made an edit in above answer. You need to implement CheckedChangeListener
0
// Define size as per your list.
     boolean[] itemChecked = new boolean[YourList.size()];


     holder.ck1.setChecked(false);

    // check its already checked..

      if (itemChecked[position])
       holder.ck1.setChecked(true);
      else
       holder.ck1.setChecked(false);

    holder.ck1.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        // TODO Auto-generated method stub
        if (holder.ck1.isChecked())
         itemChecked[position] = true;
        else
         itemChecked[position] = false;
       }
      });

1 Comment

I have tried. When I am scrolling the checked item is getting unchecked. :(
0

Try with this

private ArrayList<StudentData> selectedUserArrayList = new ArrayList<>(); // Declare globally
public static int i; // Declare globally

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

    if (view == null){
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        view = inflater.inflate(row, parent, false);

        holder = new ViewHolder();

        holder.studentName = (TextView) view.findViewById(R.id.studentName);
        holder.id = (TextView) view.findViewById(R.id.studentID);
        holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox);


        view.setTag(holder);

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

    if((data == null) || ((position+1) > data.size()))
        return view;

    studentData = data.get(position);


        viewHolder.checkbox.setOnCheckedChangeListener(null);
        viewHolder.checkbox.setChecked(selectedUserArrayList.contains(user));
        viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    i = user.getUserId();
                    selectedUserArrayList.add(user);
                } else {
                    if (i == user.getUserId()) {
                        i = 0;
                    }
                    selectedUserArrayList.remove(user);
                }
            }
        });
    if ((holder.studentName != null) && null != studentData.getName()
            && studentData.getName().trim().length() > 0 )
        holder.studentName.setText(Html.fromHtml(studentData.getName()));

    if ((holder.id != null) && null != studentData.getAcademicId()
            && studentData.getAcademicId().trim().length() > 0 )
        holder.id.setText(Html.fromHtml(studentData.getAcademicId()));


    return view;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.