2012-04-21 100 views
1

我做了一些遊戲的列表視圖,當遊戲被刪除時,我希望它在列表視圖中消失。我試圖使用adapter.notifyDataSetChanged(),但我無法讓它工作,你能幫助我嗎?在Android中更新列表視圖

public static final String MY_SETTINGS = "MySettings"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 



    DBHelpeR entry = new DBHelpeR(Loadmenu.this); 
    entry.open(); 
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames()); 

    setListAdapter(adapter); 
    entry.close(); 

    ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 
    lv.setBackgroundResource(R.drawable.background); 
    final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    lv.setOnItemLongClickListener(new OnItemLongClickListener(){ 
     public boolean onItemLongClick(AdapterView<?> parent, final View view, 
       int position, long id) { 

      String gamename = ((TextView) view).getText().toString(); 
      builder.setTitle("Slet " + gamename + "?"); 
      builder.setItems(new CharSequence[]{"Slet"} , new DialogInterface.OnClickListener() { 

       // Click listener 

       public void onClick(DialogInterface dialog, int item) { 
        DBHelpeR entry = new DBHelpeR(Loadmenu.this); 
        entry.open(); 
        int game_id = entry.getGameID(((TextView) view).getText().toString()); 
        Log.d("load",Integer.toString(game_id)); 
        entry.deleteGame(game_id); 
        entry.close(); 
        adapter.notifyDataSetChanged(); 
       } 

      }); 
      builder.show(); 
      return true; 
     } 

    }); 
} 

回答

2
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames()); 

下面替換上述行:::

ArrayList<String> entries = entry.getGameNames(); 
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entries); 

,當你刪除剛纔dcall下面再次兩條線::

entries = entry.getGameNames(); 
adapter.notifyDataSetChanged(); 

更新::

再次調用adapter.notifyDataS etChanged();撥打以下行::

final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, entry.getGameNames()); 
setListAdapter(adapter); 
+0

嗯,不工作:S它只是從第一次使用條目變量,而不是使用更新版本。 – gedemagt 2012-04-21 21:49:01

+0

現在它工作。謝謝! – gedemagt 2012-04-25 19:56:38

0

呼叫

final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames()); 
setListAdapter(adapter); 

再次調用

adapter.notifyDataSetChanged(); 

注意前:確保你已經改變了數組的變化是明顯的。

+0

以及每次創建適配器和每次設置新適配器的用途。如果他這樣做,需要調用notifyDataSetChanged() – 2012-04-21 15:21:28

+0

我會寫什麼而不是'this'?由於它在Listener內部? – gedemagt 2012-04-21 21:50:10