2014-09-19 72 views
0

好吧,讓我有一個充滿ListFragment的MemoryListActivity。我填充列表與自定義的內存對象,並使用下面添加新項目時更新自定義ArrayAdapter <Memory>以更新

public class MemoryAdapter extends ArrayAdapter<Memory> { 

private static final String TAG = "MemoryAdapter.TAG"; 
private Context context; 
private List<Memory> objects; 

public MemoryAdapter(Context context, int resource, List<Memory> memoryList) { 
    super(context,resource, memoryList); 
    this.context = context; 
    this.objects = memoryList; 


} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    Log.i(TAG, "getView entered"); 

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); 

    View view = inflater.inflate(R.layout.memory_list_item, null); 

    Memory memory = objects.get(position); 

    TextView eventTV = (TextView) view.findViewById(R.id.list_item_title); 
    eventTV.setText(memory.getEventName()); 

    TextView eventLocationTV = (TextView) view.findViewById(R.id.list_item_location); 
    eventLocationTV.setText(memory.getEventLocation()); 

    TextView numGuestsTV = (TextView) view.findViewById(R.id.list_item_guest_count); 
    numGuestsTV.setText(Integer.toString(memory.getNumGuests())); 

    return view; 
} 
} 

的MemoryAdapter.class我試圖從onActivityResult方法被稱爲更新它,當我回來,如果結果代碼是好的。

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (requestCode == NEW_MEM_CODE && resultCode == RESULT_OK) { 
     // TODO: force refresh with notifyDataSetChanged() 
     refresh(); 
    } 
} 

在這個refresh();方法中需要什麼代碼?這是我試過,但它不工作

private void refresh() { 

    MemoryListFragment frag = (MemoryListFragment) getFragmentManager().findFragmentByTag(MemoryListFragment.TAG); 

    ArrayAdapter<Memory> adapter = (ArrayAdapter<Memory>) frag.getListAdapter(); 

    adapter.notifyDataSetChanged(); 
} 
+0

更新您的適配器'yourAdapter.notifyDataSetChanged();'如果它不工作,然後重新初始化'適配器'與新數據,然後將'adapter'設置爲您的列表。 – Rustam 2014-09-19 17:11:20

+0

我應該在哪裏做這個?從包含活動還是從列表片段內? – ENG618 2014-09-19 17:23:40

+0

您需要進行一些更改,新數據在哪裏? – mmlooloo 2014-09-19 17:24:45

回答

0

這樣做:

private void refresh() { 

    memoryAdapter=MemoryAdapter(context, updatedMemoryList); 

    memoryAdapter.notifyDataSetChanged(); 
} 
+0

我試過這個,但仍然沒有什麼...'私人無效刷新(){ HashMap memories = manager.getMemories(); 列表 memoryList = new ArrayList (memories.values()); MemoryAdapter adapter = new MemoryAdapter(this,R.layout.memory_list_item,memoryList); adapter.notifyDataSetChanged();你的代碼中的 – ENG618 2014-09-19 17:38:51

+0

MemoryAdapter類已經在膨脹xml,所以'memoryAdapter = MemoryAdapter(context,updatedMemoryList);'只需要memoryadapter.notifyDataSetChanged();' – Rustam 2014-09-19 17:54:32

+0

所以我將不得不在我的ArrayAdapter類中創建一個新的方法只有這些參數? – ENG618 2014-09-19 17:57:13