Android从游标适配器删除列表项

时间:2014-04-26 07:05:44

标签: android android-cursoradapter listitem

我已经实现了CursorAdapter来显示手机联系人列表,它运行正常。现在我想在点击时实现删除项目..但项目将仅从列表中删除,而不是从手机数据库中删除..删除功能将在CursorAdapter中实现。试过但无法做到这一点..帮助我..

我的代码在这里..

ImageButton remFrnd = (ImageButton) view.findViewById(R.id.remove_frnd);
remFrnd.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        Animation fadeOut = AnimationUtils.loadAnimation(context, R.anim.request_animate);

        fadeOut.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {}

            @Override
            public void onAnimationRepeat(Animation animation) {}

            @Override
            public void onAnimationEnd(Animation animation) {

                /////////////////////////////////////////////////////////////////////////// 
                //final int position = listContacts.getPositionForView((View) view.getParent());
                // datalist.remove(position);
                deleteRecordWithId(itemId);
                cursor.requery();
                // myAdapter.notifyDataSetChanged();
                /////////////////////////////////////////////////////////
                notifyDataSetChanged();
            }
        });

        view.startAnimation(fadeOut);
    }
}

1 个答案:

答案 0 :(得分:1)

如果您只想从列表中删除条目(而不是从电话簿中删除),请确保每次触发DataSetChanged时,适配器都不会从电话簿中加载数据 - 就像游标适配器可能会这样做... 而是将电话簿中的数据加载到某个数据结构中,然后加载ArrayAdapter或类似的东西......

<强> 编辑:

private ListView initializeListView() {
    ListView lv = (ListView)findViewById(R.id.listView);
    ArrayList<Person> persons = loadPersonsFromMyChosenStorage();
    if(persons==null){
        //we haven't stored persons yet
        persons = new ArrayList<Person>();
        String whereName = ContactsContract.Data.MIMETYPE + " = ?";
        String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
        Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
        while (cursor.moveToNext()) {
            String firstname = cursor.getString(cursor.getColumnIndex(
                ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
            String lastname = cursor.getString(cursor.getColumnIndex(
                ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
            if(firstname!=null&&lastname!=null){
                persons.add(new SimplePerson(firstname,lastname));
            }
        }
        storePersonsToMyChosenStorage(persons);
    }
    if(lv!=null) {
        lv.setAdapter(new ArrayAdapter<Person>(this, android.R.layout.simple_list_item_single_choice, persons));
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
    return lv;
}