簡體   English   中英

自定義ListView復選框選擇

[英]Custom ListView checkbox selection

我正在嘗試檢查自定義listView項的checkbox

我正在嘗試在自定義列表視圖適配器上使用view.setOnClickListener

當我選擇listView項中的一項時,另一項也在列表的下方被選中。

我的getView代碼

 @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;
}

這是我的布局代碼:

  <?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>

我選擇了這個項目 該項目自動被選中

我該怎么辦?

之所以發生這種情況,是因為Listview的默認行為可以重用膨脹視圖。 使用臨時arraylist來存儲單擊的位置,並驗證相同的arraylist是否包含在getView方法內的特定位置。 在適配器類中聲明arraylist,在這里:

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

現在,按照以下方法更新getView()方法:

@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;
}

您已經兩次添加了setTag(),肯定是搞砸了。 第一次執行setTag()時,您要為復選框設置標簽,而執行getTag()時,您將使用完整的holder。

編輯:

它在滾動時重用您的視圖。 您將必須為復選框實現checkedchangelistener,並更新復選框狀態:

 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..
            }
        });

如果上面沒有幫助,還可以發布“行”布局。

// 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;
       }
      });

試試這個

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM