简体   繁体   English

在android中单击Listview的单个项目时选择ListView的多个项目

[英]Multiple Items selected of ListView when Click on Single Item of Listview in android

I have multiple items in ListView and list of item is larger than the screen size.To view all items I scroll down to the ListView .我在ListView有多个项目,项目列表大于屏幕大小。要查看所有项目,我向下滚动到ListView ListView contain one CheckBox and Two TextView . ListView包含一个CheckBox和两个TextView

在此处输入图片说明

When I select first item of the ListView other item is Also selected which is down in Scroll(which is not showing on screen and will show after scrolling).当我选择ListView第一项时,其他项也被选中,它在 Scroll 中向下(它没有显示在屏幕上,滚动后会显示)。
It work properly when I removed some items from the ListView .当我从ListView删除一些项目时,它可以正常工作。 Remaining items fit on mobile screen.The problem comes only when scrolling is added.剩余项目适合移动屏幕。只有在添加滚动时才会出现问题。 I am stuck on that problem from yesterday.我从昨天开始就被这个问题困住了。

 ListView lv=findViewById(R.id.listOfStudents);
 Cursor cursor = dbHelper.fetchAllData();
 final String[] columns = new String[]{CountriesDbAdapter.KEY_NAME, CountriesDbAdapter.KEY_CONTACT};
 int[] to = new int[]{R.id.name, R.id.phone};
 dataAdapter = new SimpleCursorAdapter(this, R.layout.student_info, cursor, columns, to, 0);
 lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
 lv.setAdapter(dataAdapter);
 lv.setOnItemClickListener(new OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
         CheckBox checkBox = (CheckBox) listView.getAdapter().getView(position,view , null).findViewById(R.id.checkBox);
         if (checkBox.isChecked()) {
             checkBox.setChecked(false);
         } else {
             checkBox.setChecked(true);
         }
     }
 });

code for adapter.适配器代码。 CountriesDbAdapter.java国家数据库适配器.java

package com.example.usmanasghar.studentattendancefromdatabase;

/**
 * Created by Usman Asghar on 09/02/2016.
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

    public class CountriesDbAdapter {

        public static final String KEY_ROWID = "_id";
        public static final String KEY_NAME = "name";
        public static final String KEY_CONTACT = "contact";
        public static final String KEY_PRESENT = "Present";
        private static final String TAG = "CountriesDbAdapter";
        private DatabaseHelper mDbHelper;
        private SQLiteDatabase mDb;

        private static final String DATABASE_NAME = "ClassRoom";
        private static final String SQLITE_TABLE = "StudentInfo";
        private static final int DATABASE_VERSION = 1;

        private final Context mCtx;

        private static final String DATABASE_CREATE =
                "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
                        KEY_ROWID + " integer PRIMARY KEY autoincrement," +
                        KEY_NAME + "," +
                        KEY_CONTACT +
                        ");";


        private static class DatabaseHelper extends SQLiteOpenHelper {

            DatabaseHelper(Context context) {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }


            @Override
            public void onCreate(SQLiteDatabase db) {
                Log.w(TAG, DATABASE_CREATE);
                db.execSQL(DATABASE_CREATE);
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
                db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
                onCreate(db);
            }
        }

        public CountriesDbAdapter(Context ctx) {
            this.mCtx = ctx;
        }

        public CountriesDbAdapter open() throws SQLException {
            mDbHelper = new DatabaseHelper(mCtx);
            mDb = mDbHelper.getWritableDatabase();
            return this;
        }

        public void close() {
            if (mDbHelper != null) {
                mDbHelper.close();
            }
        }

        public long createCountry(String name,
                                  String contact) {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_NAME, name);
            initialValues.put(KEY_CONTACT, contact);
            return mDb.insert(SQLITE_TABLE, null, initialValues);
        }

        public int deleteStudentWithId(String id) {
            int doneDelete;
            doneDelete = mDb.delete(SQLITE_TABLE, "_id= ?", new String[]{id});//Delete from table where _id=?
            return doneDelete;
        }
       public Cursor fetchContactsWithId(String id){
           Cursor mCursor = null;
           if (id == null || id.length() == 0) {
               mCursor = mDb.query(SQLITE_TABLE, new String[]{KEY_ROWID, KEY_NAME, KEY_CONTACT},
                       null, null, null, null, null);
           } else {
               mCursor = mDb.query(true, SQLITE_TABLE, new String[]{KEY_ROWID, KEY_NAME,KEY_CONTACT},
                       KEY_ROWID + " like '%" + id + "%'", null,
                       null, null, null, null);
           }
           if (mCursor != null) {
               mCursor.moveToFirst();
           }
           return mCursor;
        }
        public void UpdateData(String Name, String PhoneNumber, String id) {
            ContentValues cv = new ContentValues();
            cv.put(KEY_NAME, Name);
            cv.put(KEY_CONTACT, PhoneNumber);
            mDb.update(SQLITE_TABLE, cv, "_id = ?", new String[]{id});
        }

        public Cursor fetchCountriesByName(String inputText) throws SQLException {
            Cursor mCursor = null;
            if (inputText == null || inputText.length() == 0) {
                mCursor = mDb.query(SQLITE_TABLE, new String[]{KEY_ROWID, KEY_NAME, KEY_CONTACT},
                        null, null, null, null, null);
            } else {
                mCursor = mDb.query(true, SQLITE_TABLE, new String[]{KEY_ROWID, KEY_NAME, KEY_CONTACT},
                        KEY_NAME + " like '%" + inputText + "%'", null,
                        null, null, null, null);
            }
            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;

        }

        public Cursor fetchAllData() {
            Cursor mCursor = mDb.query(SQLITE_TABLE, new String[]{KEY_ROWID, KEY_NAME, KEY_CONTACT},
                    null, null, null, null, null);

            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;
        }
        public Cursor fetchOnlyContacts() {
            Cursor mCursor = mDb.query(SQLITE_TABLE, new String[]{ KEY_CONTACT},
                    null, null, null, null, null);

            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;
        }

        public void insertSomeCountries() {
            createCountry("Jordan", "03096759397");
            createCountry("Liza", "03094711934");
            createCountry("Johny", "03321625972");
            createCountry(Xeomia", "03088800088");
            createCountry("Shina", "03058825525");


        }

    }

The issue with CheckBox inside ListView is that the view gets recycled due to recycling of ListView and the value of Checkbox(check or uncheck) is not maintained. ListView 中的 CheckBox 的问题在于,由于 ListView 的回收,视图被回收,并且 Checkbox(选中或取消选中)的值没有得到维护。 To, maintain the state to CheckBox there has to be something that can store the state of Checkbox.为了保持 CheckBox 的状态,必须有一些东西可以存储 Checkbox 的状态。

@Lalit Poptani have written a blog for ListView with CheckBox Scrolling Issue @Lalit PoptaniListView写了一篇关于CheckBox Scrolling Issue的博客

ListView used recycling of Views created earlier. ListView 使用了之前创建的 Views 的回收。 When ListView created it's create the number of View plus one which can be show able on screen when you scroll the screen previous view get recycle by replacing content of it eg - when 5 rows are displaying on screen and you scroll down then first row of view content replace by 6 position row that's the reason another item get selected when you scrolling.当 ListView 创建时,它会创建 View 的数量加一个,当您滚动屏幕时,可以在屏幕上显示前一个视图通过替换它的内容来回收,例如 - 当屏幕上显示 5 行并且向下滚动然后第一行视图时内容替换为 6 个位置行,这就是滚动时选择另一个项目的原因。 You need to update data value of checkbox for perticular row not the checkbox of row.您需要更新特定行的复选框的数据值,而不是行的复选框。

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

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