2011-09-10 17 views
7

Tôi đang mở rộng BaseAdapter để tạo một hàng listview tùy chỉnh. Tôi có trình đơn ngữ cảnh mở ra mọi lúc người dùng giữ trên hàng và nhắc nhở nếu anh ta muốn xóa nó. Tuy nhiên, làm cách nào để xóa hàng? Hashmap chỉ là dữ liệu thử nghiệm.Làm cách nào để xóa một mục khỏi bộ tiếp hợp cơ sở tùy chỉnh của tôi?

private MyListAdapter myListAdapter; 
private ArrayList<HashMap<String, String>> items; 

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

    items = new ArrayList<HashMap<String,String>>(); 
    HashMap<String, String> map1 = new HashMap<String, String>(); 
    map1.put("date", "10/09/2011"); 
    map1.put("distance", "309 km"); 
    map1.put("duration", "1t 45min"); 
    items.add(map1); 

    myListAdapter = new MyListAdapter(this, items); 
    setListAdapter(myListAdapter); 
    getListView().setOnCreateContextMenuListener(this); 
} 


private class MyListAdapter extends BaseAdapter { 

    private Context context; 
    private ArrayList<HashMap<String, String>> items; 

    public MyListAdapter(Context context, ArrayList<HashMap<String, String>> items) { 
     this.context = context; 
     this.items = items; 
    } 

    @Override 
    public int getCount() { 
     return items.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return items.get(position); 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     View view = convertView; 

     if (view == null) { 
      LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      view = layoutInflater.inflate(R.layout.row_log, null); 
     } 

     TextView rowLogOverview = (TextView) view.findViewById(R.id.rowLogOverview); 

     HashMap<String, String> item = items.get(position); 
     rowLogOverview.setText(item.get("date")); 

     return view; 
    } 
} 

Trả lời

15

Bạn không xóa khỏi bộ điều hợp! Bạn xóa khỏi các mục! và bộ điều hợp nằm giữa các mục của bạn và chế độ xem. Từ quan điểm bạn có thể nhận được vị trí và theo vị trí bạn có thể xóa các mục. Sau đó, bộ điều hợp sẽ làm mới chế độ xem của bạn.

Điều đó có nghĩa bạn cần phải làm điều gì đó như thế này

items.remove(position); 
adapter.notifyDataSetChanged() 
+1

gọi 'adapter.notifyDataSetChanged()' vào bộ điều hợp được gắn với 'mục' sẽ cập nhật listView. – Aryo

1
  1. mục remove từ mục
  2. gọi BaseAdapter.notifyDataSetChanged(). Sau đó listview sẽ được vẽ lại và hàng mục tiêu sẽ bị xóa khỏi màn hình.
9

Để xóa, bạn sẽ cần phải làm 2 việc:

  1. Gọi .remove() trên ArrayList của bạn (bài).
  2. Gọi .notifyDataSetChanged() trên bản sao của lớp học MyListAdapter của bạn (mListAdapter).
Các vấn đề liên quan