ListView onItemLongClick视图isSelected始终返回False

时间:2018-04-05 09:10:07

标签: android listview simplecursoradapter onlongclicklistener

我有一个扩展ListFragment并使用SimpleCursorAdapter的类。我创建了2个按钮,使用户可以选择/取消选择列表中的所有内容,这样可以正常工作。列表中可能有200个项目,因此如果他们只想选择其中的190个,则可以选择全部200个,然后取消选择10个。

ListView使用setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

问题是我希望用户能够通过长按行来单独取消选择行。我在setOnItemLongClickListener上使用ListView,但view.isSelected始终返回false,即使选择了该行。

有谁知道为什么会这样。

我已将日志声明用于证明这一事实。

我也看过网络,有些帖子说可能的问题是我使用SimpleCursorAdapter并且它太基本了。

我对适配器,列表和触摸事件不是特别擅长,所以有人能指出我正确的方向吗?

我认为应该解决这个问题,这就是为什么isSelected方法总是返回false。

public  class  CarerListForGroupMessageFragment extends ListFragment {

    private static final String TAG =  CarerListForGroupMessageFragment.class.getSimpleName();
    RROnCallApplication rrOnCallApp;
    Cursor cursor;
    ListView listView;
    MyAdapter myAdapter;
    OnCarerForGroupMessageSelectedListener mListener;
    EditText etext;
    Button resetSearch;
    Button selectAll;
    Button deselectAll;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        rrOnCallApp = (RROnCallApplication) getActivity().getApplicationContext();

        cursor = getCarerList(null);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragmentcarerlistforgroupmessage, container, false);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        String[] from = new String[]{DBModel.C_CARER_FIRSTNAME, DBModel.C_CARER_LASTNAME, DBModel.C_CARER_PHONENUMBER};
        int[] to = {R.id.carerrowfirstname, R.id.carerrowlastname, R.id.carerrowtelno};

        myAdapter = (MyAdapter) new MyAdapter(getActivity(),R.layout.carerrow , cursor, from, to);

        setListAdapter(myAdapter);
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        getListView().setFastScrollEnabled(true);
        getListView().setTextFilterEnabled(true);    

selectAll = (Button) getActivity().findViewById(R.id.carerlistselectallgroupmessage);
        selectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {    
                for(int i = 0; i < cursor.getCount(); i++){
                    getListView().setItemChecked(i, true);
                }

                myAdapter.notifyDataSetChanged();
            }
        });

        deselectAll = (Button) getActivity().findViewById(R.id.carerlistdeselectallgroupmessage);
        deselectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(int i = 0; i < cursor.getCount(); i++) {
                    getListView().setItemChecked(i, false);
                }

                myAdapter.notifyDataSetChanged();
            }
        });

 getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(getActivity(), "On long click listener", Toast.LENGTH_LONG).show();

                boolean ret = false;
                if(! view.isSelected()) {

                    //row in list is not currently selected, so set it as selected
                    Log.e(TAG, "row postion " + position + " in list is not currently selected");

                    view.setSelected(true);

                    Cursor cursor = (Cursor) getListAdapter().getItem(position);

                    String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
                    String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
                    String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
                    String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));

                    Log.e(TAG, "carerID = " + carerID);

                    mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);

                    getListView().setItemChecked(position, true);
                    myAdapter.notifyDataSetChanged();

                    ret = true;

                } else {
                    Log.e(TAG, "row " + position + " in list is currently selected");

                    view.setSelected(false);

                    Cursor cursor = (Cursor) getListAdapter().getItem(position);

                    String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
                    String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
                    String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
                    String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));

                    Log.e(TAG, "carerID = " + carerID);

                    mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);

                    getListView().setItemChecked(position, false);
                    myAdapter.notifyDataSetChanged();
                    ret = true;
                }

                return  ret;
            }
        });
    } // End of onActivityCreated


// Container Activity must implement this interface
public interface OnCarerForGroupMessageSelectedListener {
    public void onCarerForGroupMessageSelected(String carerId, String carerFirstName, String carerLastName, String carerTelNo ,boolean longClick);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnCarerForGroupMessageSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnCarerForGroupMessageSelectedListener");
    }
}

 @Override
public void onListItemClick(ListView l, View v, int position, long id) {
    Log.e(TAG, "in onListItemClick");
    v.setSelected(true);

    //v.setBackgroundColor(Color.parseColor("#FF0000"));

    TextView carerName = (TextView) getView().findViewById(R.id.textviewcarername);

    Cursor cursor = (Cursor) getListAdapter().getItem(position);

    String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
    String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
    String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
    String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));

    Log.e(TAG, "carerID = " + carerID);

    mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, false);

    getListView().setItemChecked(position, true);
    myAdapter.notifyDataSetChanged();
}

private class MyAdapter extends SimpleCursorAdapter {

    @SuppressWarnings("deprecation")
    public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
    }

    @Override
    public
    View getView(int position, View convertView, ViewGroup parent) {
        Log.e(TAG, "inside myadapter getview");
        View v = super.getView(position, convertView, parent);
        if(v == null)
            return null;

        Log.e(TAG, "clicked the listview!");

        //Cursor c = (Cursor)getItem(position);
        // String tagScanTime = c.getString(c.getColumnIndex(LoginValidate.C_TAG_SCAN_TIME));

        // ((TextView)v.findViewById(R.id.rowcarername)).setText(name + " signed " + status +" at ");

        return v;
    }
}} //end of CarerListFragment

[编辑1]

DBModel类

public class DBModel {



    private static final String TAG = DBModel.class.getSimpleName();





    // table carer column names
        public static final String C_CARER_ID_INDEX = BaseColumns._ID;
        public static final String C_CARER_ID = "carerid";
        public static final String C_CARER_FIRSTNAME = "carerfirstname";
        public static final String C_CARER_LASTNAME = "carerlastname";
        public static final String C_CARER_PHONENUMBER = "carerphonenumber";
        public static final String C_CARER_EMAIL = "careremail";




Context context;
    DBHelper dbhelper;
    RROnCallApplication rrOnCallApplication;



    public DBModel(Context context) {

        this.context = context;
        dbhelper = new DBHelper();
        rrOnCallApplication = (RROnCallApplication) context.getApplicationContext();


    }






/**
     * inner class to create/open/upgrade database
     * 
     * @author matt
     * 
     */
    private class DBHelper extends SQLiteOpenHelper {

        // database name and version number
        public static final String DB_NAME = "roadrunneroncall.db";
        public static final int DB_VERSION = 3;

        // table names


        public static final String TABLECARER = "carer";


        public DBHelper() {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            Log.e(TAG, "SQLiteOpenHelper oncreate ");



String sqlToCreateCarerTable = String
                    .format("create table %s ( %s INTEGER primary key, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT)",
                            TABLECARER, C_CARER_ID_INDEX, C_CARER_ID, C_CARER_FIRSTNAME,
                            C_CARER_LASTNAME, C_CARER_PHONENUMBER, C_CARER_EMAIL);

            db.execSQL(sqlToCreateCarerTable);
            Log.e(TAG, "oncreate " + sqlToCreateCarerTable);

}




        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {





        }//end of onUpgrade

    }//end of DBHelper


public  SQLiteDatabase getDB(){

        return dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());

    }



public void deleteTableCarer() {
        // open database
        SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());

        // delete contents of table
        db.delete(DBHelper.TABLECARER, null, null);

        // close database
        // db.close();
    }


    public void insertIntoCarer(ContentValues cv) {

        SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());

        db.insertWithOnConflict(DBHelper.TABLECARER, null, cv, SQLiteDatabase.CONFLICT_REPLACE);

        // db.close();

    }



    public Cursor queryAllFromCarer() {

        // open database
        SQLiteDatabase db = dbhelper.getReadableDatabase(RROnCallApplication.getSecretKey().toString());

        return db.query(DBHelper.TABLECARER, null, null, null, null, null, null);

    }

1 个答案:

答案 0 :(得分:3)

请检查此代码。

if(! view.isSelected())

而不是

{{1}}

并在DBModel类中保留布尔标志值。