更新自定义ArrayAdapter <memory>以在添加新项目时更新</memory>

时间:2014-09-19 16:40:54

标签: android android-listfragment

好的,我有一个MemoryListActivity填充了ListFragment。我使用自定义Memory对象填充列表,并使用下面的MemoryAdapter.class

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;
}
}

如果结果代码没问题,我试图从我回来时调用的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();
}

1 个答案:

答案 0 :(得分:0)

这样做:

private void refresh() {

    memoryAdapter=MemoryAdapter(context, updatedMemoryList);

    memoryAdapter.notifyDataSetChanged();
}