开发者

How would i delete a listitem from a listview?

The Listitem would not be retrieved from the开发者_StackOverflow db. It is passed over from another class.


You don't "delete a listitem from a listview". You modify the data held by the ListAdapter that is supporting the ListView. If the adapter is an ArrayAdapter, call remove() on the ArrayAdapter. If the adapter is a CursorAdapter, remove the item from the database and requery() the Cursor. And so on.


Better if you use a SimpleAdapter which takes an ArrayList.Then you update your list by removing what you want to remove & just call adapter.notifyDataSetChanged().Like:

static final ArrayList<HashMap<String,String>> list =new ArrayList<HashMap<String,String>>();


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

        setContentView(R.layout.newentrypagelayout);
        //create base adapter for listview
        adapter= new SimpleAdapter(
                this,
                list,
                R.layout.custom_list_row,
                new String[] {"pen","price","color"},
                new int[] {R.id.text1,R.id.text2, R.id.text3}

                );
            populateList();
            setListAdapter(adapter);


}

public void populateList()
{      
sHashMap<String,String> temp = new HashMap<String,String>();
            temp.put("pen","MONT Blanc");
            temp.put("price", "200.00$");
            temp.put("color", "Silver, Grey, Black");
            list.add(temp);
            HashMap<String,String> temp1 = new HashMap<String,String>();
            temp1.put("pen","Gucci");
            temp1.put("price", "300.00$");
            temp1.put("color", "Gold, Red");
            list.add(temp1);
            HashMap<String,String> temp2 = new HashMap<String,String>();
            temp2.put("pen","Parker");
            temp2.put("price", "400.00$");
            temp2.put("color", "Gold, Blue");
            list.add(temp2);
            HashMap<String,String> temp3 = new HashMap<String,String>();
            temp3.put("pen","Sailor");
            temp3.put("price", "500.00$");
            temp3.put("color", "Silver");
            list.add(temp3);
            HashMap<String,String> temp4 = new HashMap<String,String>();
            temp4.put("pen","Porsche Design");
            temp4.put("price", "600.00$");
            temp4.put("color", "Silver, Grey, Red");
            list.add(temp4);

}
now if you need to delete an item.Get the selected index(the item that has been selected) remove it from the array list & call the method I told before.Like:

public void itemDeleteButtonClicked(View v)
     {
            int index=itemsListView.getSelectedItemPosition();
            list.remove(index);
            adapter.notifyDataSetChanged();

     }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜