Android listview中CheckBox选中混乱的情况

时间:2021-11-13 19:45:41

        最近在写Android界面时经常用到listview这个控件,个人认为其缺陷很多,比如快速滑动时,会出现加载缓慢,不能缓存加载过得数据,每次滑动时都要加载控件的ID,所以须有将listview优化,下面将讲讲我遇到的问题。 在listview 中加入CheckBox时,选中第一个,当往下滑动时,出现了下面没有选中的也被选中的情况,下面看看截图。

Android listview中CheckBox选中混乱的情况              Android listview中CheckBox选中混乱的情况  

我在第一张图中选中了第一个和第二个CheckBox,将其后面的数量分别加到5和3,但是玩下滑动时,发现,在第7个和第8个item中,CheckBox也被选中,其后面的数量也和之前第一个和第二个一样。出现这种情况的原因就是我的listview在我的手机屏幕上只能加载6个item,在加载第一个时,会出现重复调用,后来我调整了listview的高度,将其调整为fill_parent 也是不行,后来在网上找到很多资料发现解决方法都太繁琐,我自己就写了一个简单的方法。

   解决方法:

我的方法就是将CheckBox的选中状态保存起来,每次加载时,就会判断这个状态,这样就不会重复加载了。下面来看代码

先是Adapter的代码:

package com.example.book;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.List;

/**
 * Created by THINK on 2017/10/28.
 */

public class MygouwuchebookAdapter extends ArrayAdapter<Mygouwuchebookclass>
{
    private int resourseId;
    private Context context;
    private static boolean[] checks;//定义数组来保存CheckBox的状态 private String[] booknum;//同样定义数组来保存Textview的状态 private int length;//定义一个长度,来获取listview 的长度
    public MygouwuchebookAdapter(Context context, int textViewResourseId, List<Mygouwuchebookclass> objects)
    {
        super(context,textViewResourseId,objects);
        resourseId=textViewResourseId;
        this.context=context;
       checks = new boolean[objects.size()];//初始化数组
        booknum=new String[objects.size()];
        length=objects.size();
        for(int i=0;i<objects.size();i++)//这里是我的text的初始化text,为1
        {
            booknum[i]="1"; }
    }
    @Override
    public View getView(final int position, View  converView, ViewGroup parent)
    {
        Mygouwuchebookclass mygouwuchebookclass=getItem(position);
        View view;
        final ViewHolder viewHolder;
        if(converView==null)
        {
            view = LayoutInflater.from(getContext()).inflate(resourseId, parent, false);
            viewHolder=new ViewHolder();
            viewHolder.mygouwuchexuanze=(CheckBox) view.findViewById(R.id.Mygouwuchexuanze);
            viewHolder.mygouwuchebookimage=(ImageView)view.findViewById(R.id.mygouwuchebook);
            viewHolder.mygouwuchebookname=(TextView)view.findViewById(R.id.Mygouwuchebookname);
            viewHolder.mugouwuchebookprice=(TextView)view.findViewById(R.id.Mygouwuchebookprice);
            viewHolder.mygouwuchebooknum=(TextView)view.findViewById(R.id.Mygouwuchebooknum);
            viewHolder.mygouwuchebooknumjian=(Button)view.findViewById(R.id.Mygouwuchebooknumjian);
            viewHolder.mygouwuchebooknumjia=(Button)view.findViewById(R.id.Mygouwuchebooknumjia);
            viewHolder.mygouwuchebookshanchu=(Button)view.findViewById(R.id.Mygouwuchebookshanchu);
            view.setTag(viewHolder);
        }
        else
        {
            view=converView;
            viewHolder=(ViewHolder)view.getTag();
        }
        final int pos  = position;//定义一个final的int类型pos用来记录点击的位置
        viewHolder.mygouwuchexuanze.setFocusable(false);
        viewHolder.mygouwuchebooknumjian.setFocusable(false);
        viewHolder.mygouwuchebooknumjia.setFocusable(false);
        viewHolder.mygouwuchebookshanchu.setFocusable(false);
        viewHolder.mygouwuchebooknumjian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(viewHolder.mygouwuchebooknum.getText().toString().equals("1"))
                {

                }
                else
                {
                    viewHolder.mygouwuchebooknum.setText(String.valueOf(Integer.parseInt(viewHolder.mygouwuchebooknum.getText().toString())-1));
                    booknum[pos]=String.valueOf(Integer.parseInt(viewHolder.mygouwuchebooknum.getText().toString()));
                    //text的text改变时,将text保存进数组里面
                }


            }
        });
        viewHolder.mygouwuchebooknumjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                viewHolder.mygouwuchebooknum.setText(String.valueOf(Integer.parseInt(viewHolder.mygouwuchebooknum.getText().toString())+1));
               booknum[pos]=String.valueOf(Integer.parseInt(viewHolder.mygouwuchebooknum.getText().toString()));
                //text的text改变时,将text保存进数组里面
            }
        });

        viewHolder.mygouwuchebookshanchu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,position+"查看",Toast.LENGTH_LONG).show();
            }
        });
        viewHolder.mygouwuchebookimage.setImageResource(mygouwuchebookclass.getImageviewId());
        viewHolder.mygouwuchebookname.setText(mygouwuchebookclass.getBookname());
        viewHolder.mugouwuchebookprice.setText(String.valueOf(mygouwuchebookclass.getPrice()));
        //pos必须声明为final
        //下面是CheckBox的点击事件,
        viewHolder.mygouwuchexuanze.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                checks[pos] = isChecked;//当被选中时,将该位置的CheckBox的状态保存下来
            }});
        viewHolder.mygouwuchexuanze.setChecked(checks[pos]);//每次加载这个item时,将CheckBox的状态赋值就OK了
        viewHolder.mygouwuchebooknum.setText(booknum[pos]);//每次加载item时,给TextView的text赋值就OK了
        return  view;
    }

    public static boolean[] getChecks() {
        return checks;
    }

    public static void setChecks(boolean[] checks) {
        MygouwuchebookAdapter.checks = checks;
    }
    /*public void quanxuan(boolean ischecked)
    {
        for(int i=0;i<length;i++)
        {
            checks[i]=ischecked;
        }
    }
    public void quanbuxuan()
    {
        for(int i=0;i<length;i++)
        {
            checks[i]=false;
        }
    }*/

    class ViewHolder
    {
        CheckBox mygouwuchexuanze;
        ImageView mygouwuchebookimage;
        TextView mygouwuchebookname;
        TextView mugouwuchebookprice;
        TextView mygouwuchebooknum;
        Button mygouwuchebooknumjian;
        Button mygouwuchebooknumjia;
        Button mygouwuchebookshanchu;
        CheckBox mygouwuchequanxuan;
    }
}

下面是主活动:

package com.example.book;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MygouwucheActivity extends AppCompatActivity
{
    private List<Mygouwuchebookclass> mydianpubookclassList=new ArrayList<>();
    private  MygouwuchebookAdapter mygouwuchebookAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mygouwuche);
        inits();//初始化list
        mygouwuchebookAdapter=new MygouwuchebookAdapter(MygouwucheActivity.this,R.layout.mygouwuchebook,mydianpubookclassList);
        ListView listView=(ListView)findViewById(R.id.mygouwuchelistview);
        listView.setAdapter(mygouwuchebookAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
            {

                Toast.makeText(MygouwucheActivity.this,position+"sss",Toast.LENGTH_LONG).show();
            }
        });
       /*CheckBox checkBoxquanxuan=(CheckBox)findViewById(R.id.mygouwuchecheckBox);
        checkBoxquanxuan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

                    mygouwuchebookAdapter.quanxuan(isChecked);
                    mygouwuchebookAdapter.notifyDataSetChanged();
            }});*/


    }
  
    }
    public void inits() {
        for (int i = 0; i < 3; i++)
        {
            Mygouwuchebookclass mygouwuchebookclass = new Mygouwuchebookclass(R.drawable.gonglue, "数据结构对对对点点滴滴", 3);
            mydianpubookclassList.add(mygouwuchebookclass);
            Mygouwuchebookclass mygouwuchebookclass1 = new Mygouwuchebookclass(R.drawable.fenlei, "数据结构对对对点点滴滴", 5);
            mydianpubookclassList.add(mygouwuchebookclass1);
            Mygouwuchebookclass mygouwuchebookclass2 = new Mygouwuchebookclass(R.drawable.fenlei, "数据结构对对对点点滴滴", 6);
            mydianpubookclassList.add(mygouwuchebookclass2);
            Mygouwuchebookclass mygouwuchebookclass3 = new Mygouwuchebookclass(R.drawable.shopping, "数据结构对对对点点滴滴", 2);
            mydianpubookclassList.add(mygouwuchebookclass3);
            Mygouwuchebookclass mygouwuchebookclass4 = new Mygouwuchebookclass(R.drawable.fenlei, "数据结构对对对点点滴滴", 8);
            mydianpubookclassList.add(mygouwuchebookclass4);
            Mygouwuchebookclass mygouwuchebookclass5 = new Mygouwuchebookclass(R.drawable.shopping, "数据结构对对对点点滴滴", 1);
            mydianpubookclassList.add(mygouwuchebookclass5);
            Mygouwuchebookclass mygouwuchebookclass6 = new Mygouwuchebookclass(R.drawable.gonglue, "数据结构对对对点点滴滴", 0);
            mydianpubookclassList.add(mygouwuchebookclass6);
    }

    }
}

下面是主活动的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_mygouwuche"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.book.MygouwucheActivity">
   

    <LinearLayout
        android:id="@+id/mygouwuchelayout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/Mygouwuchetoolbar"
        android:layout_alignParentStart="true">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_below="@+id/Mygouwuchetoolbar"
            android:layout_alignParentStart="true"
            android:id="@+id/mygouwuchelistview" />
       

    </LinearLayout>




</RelativeLayout>

listview的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.book.MainActivity"
    android:background="#FFFFFFFF">


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_marginTop="11dp"
        android:weightSum="1"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_height="110dp">

        <CheckBox
            android:layout_gravity="center"
            android:layout_height="match_parent"
            android:layout_marginLeft="15dp"
            android:layout_width="30dp"
            android:id="@+id/Mygouwuchexuanze"
            android:button="@drawable/checkboxseletor"/>

        <ImageView
            app:srcCompat="@color/colorPrimary"
            android:id="@+id/mygouwuchebook"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="15dp"
            android:layout_width="70dp"
            android:layout_height="90dp" />

        <LinearLayout
            android:orientation="vertical"
            android:layout_height="110dp"
            android:layout_width="80dp">
            <TextView
                android:text="TextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="15dp"
                android:textSize="15sp"
                android:id="@+id/Mygouwuchebookname" />

            <TextView
                android:text="TextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="15dp"
                android:textSize="15sp"
                android:textColor="@android:color/holo_red_light"
                android:id="@+id/Mygouwuchebookprice" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="110dp">
            <Button
                android:text="-"
                android:textSize="40dp"
                android:layout_height="match_parent"
                android:id="@+id/Mygouwuchebooknumjian"
                android:layout_width="30dp"
                android:background="#FFFFFFFF"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#979696" />
            <TextView
                android:layout_gravity="center"
                android:layout_marginLeft="5dp"
                android:textSize="25dp"
                android:text="1"
                android:layout_height="wrap_content"
                android:id="@+id/Mygouwuchebooknum"
                android:layout_width="30dp"
                android:textDirection="inherit" />
            <Button
                android:text="+"
                android:textSize="30dp"
                android:layout_height="match_parent"
                android:id="@+id/Mygouwuchebooknumjia"
                android:layout_width="30dp"
                android:background="#FFFFFFFF"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#979696" />

            <Button
                android:text="删除"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/Mygouwuchebookshanchu"
                android:background="#FFFFFFFF"
                android:layout_weight="1" />
        </LinearLayout>



    </LinearLayout>

</RelativeLayout>

加红色标记的为解决方案,我这里的listview是经过优化之后的,如果对listview优化不懂得可以先看看资料了解一下,看了我的代码是不是很简单就解决了这个问题呢?如果还有不懂得可以来问我。

未经本人许可不能随意转载该博文。