2012-09-11 59 views
0

我有一個項目清單在我的應用程序類:notifyDataSetChanged的Android的ListView

public class MyApp extends Application { 
    private static ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); 
    //GET AND SET 
} 

我會在ListView中使用它。 我有一個按鈕,在MyApp的列表中添加一個元素:

public void addBase(View view){ 
    MyApp.add2List(....); //add to MyApp.list 
    adapter.notifyDataSetChanged(); 
} 

而在相同的活動我設置的ListView:

list=(ListView)findViewById(R.id.list_view);   
adapter=new MyListAdapter(this, R.layout.list_item, Session.getList()); 
list.setAdapter(adapter); 

這是我的適配器:

public class MyListAdapter extends ArrayAdapter<HashMap<String, String>> { 

    private Context _context; 
    private Activity activity; 
    private ArrayList<HashMap<String, String>> data; 
    private static LayoutInflater inflater=null; 

    public MyListAdapter(Context context, int resourceId, ArrayList<HashMap<String, String>> items) { 
    super(context, resourceId, items); 
    this.data = items; 
    _context = context; 
    activity = ((Activity)context); 
    inflater = activity.getLayoutInflater();  
    } 


    public View getView(final int position, View convertView, ViewGroup parent) { 
     View vi=convertView; 
     final ArrayList<HashMap<String, String>> list = Session.getList(); 
     if(convertView==null){ 
     vi = inflater.inflate(R.layout.list_item, null); 

     ImageButton delete = (ImageButton)vi.findViewById(R.id.delete_item); 
     delete.setOnClickListener(new Button.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         list.remove(position); 
         notifyDataSetChanged(); 
        } 
       }); 

     } 
     return vi; 
    } 

我使用notifyDataSetChanged()方法,但它不工作!沒有更新到列表視圖。
如果再次嘗試創建適配器,則添加按鈕將起作用。

adapter=new MyListAdapter(this, R.layout.list_item, Session.getList()); 
list.setAdapter(adapter); 

我該怎麼做刪除按鈕?
爲什麼notifyDataSetChanged()方法不起作用?

+0

嘗試'Session.getList()。add(...)' –

+0

我的add2List()方法做到了。在刪除方法中,我嘗試了它,但沒有。 – enfix

回答

0

我解決它重新每次適配器。
不是很好的解決方案,但它是我找到的唯一。

+0

這不是標準的編程習慣。 – Mahesh

-1

試試這個

Adapter.clear() 
for (HashMap <String,String> object : Session.getList()) 
Adapter.add(object) 
+0

不起作用! – enfix

+0

這不正確的方式來處理適配器 – Mahesh

1

不要重新創建要傳遞給適配器的ArrayList或Array的對象,只需再次修改相同的ArrayList或Array。並且在修改適配器後數組或arrylist大小不變時,那麼notifydatasetchange將不起作用。

在shot中它只在array或arraylist大小增加或減少時才起作用。

+0

不要讓你的整個帖子**再次像這樣大膽**。 –

相關問題