listView没有更新,直到我从片段向上导航然后返回?

时间:2014-01-22 18:34:33

标签: android android-listview android-fragments

我为我头衔的尴尬措辞道歉,我不确定如何简洁地提出这个问题。我在名为TaskListFragment的片段中有一个listView。用户从CourseListFragment中选择课程后,将启动此片段,并显示该课程的任务列表。从这里,用户可以添加任务。保存该任务后,它们将返回到TaskListFragment,此任务不会出现。如果向上导航以返回CourseListFragment然后再次选择该课程,则该任务将显示在列表中。同样,如果我尝试删除任务,它仍会显示在列表中,直到我向上导航并再次返回。知道为什么会这样吗?

以下是我的TaskListFragment:

public class TaskListFragment extends ListFragment {

private ArrayList<Task> mTasks;
private  static String courseName;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    setHasOptionsMenu(true);
    courseName = getActivity().getIntent().getStringExtra("name");
    getActivity().setTitle(courseName);
    ArrayList<Task> alltasks = TaskLab.get(getActivity()).getTasks();
    mTasks = filterTasks(alltasks);
    TaskAdapter adapter = new TaskAdapter(mTasks);
    setListAdapter(adapter);
    adapter.notifyDataSetChanged();
}

private ArrayList<Task> filterTasks(ArrayList<Task> tasks) {
    ArrayList<Task> filteredTasks = new ArrayList<Task>();
    for (Task t: tasks) {
        if (t.getBelongsToCourse().equals(courseName)) {
            filteredTasks.add(t);
        }
    } 
    return filteredTasks;
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    //Get the Task from the adapter
    Task t = ((TaskAdapter)getListAdapter()).getItem(position);
    // Start TaskActivity for this task
    Intent i = new Intent(getActivity(), TaskActivity.class);
    i.putExtra(TaskFragment.EXTRA_TASK_ID, t.getId());
    startActivity(i);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.fragment_task_list, menu);
} 

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_item_new_task:
        Task task = new Task();
        task.setBelongsToCourse(courseName);
        TaskLab.get(getActivity()).addTask(task);
        Intent i = new Intent(getActivity(), TaskActivity.class);
        i.putExtra(TaskFragment.EXTRA_TASK_ID, task.getId());
        startActivityForResult(i, 0);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    getActivity().getMenuInflater().inflate(R.menu.task_list_item_context, menu);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
        Bundle savedInstanceState) {
    View v = super.onCreateView(inflater, parent, savedInstanceState);
    ListView listView = (ListView)v.findViewById(android.R.id.list);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

    listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        public void onItemCheckedStateChanged(ActionMode mode, int position,
                long id, boolean checked) {
            // Required, but not used in this implementation
        }

        // ActionMode.Callback methods
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.task_list_item_context, menu);
            return true;
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
            // Required, but not used in this implementation
        }
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.menu_item_delete_task:
                TaskAdapter adapter = (TaskAdapter)getListAdapter();
                TaskLab taskLab = TaskLab.get(getActivity());
                for (int i = adapter.getCount() - 1; i >= 0; i--) {
                    if (getListView().isItemChecked(i)) {
                        taskLab.deleteTask(adapter.getItem(i));
                    }
                }
                mode.finish();
                adapter.notifyDataSetChanged();
                return true;
            default:
                return false;
            }
        }

        public void onDestroyActionMode(ActionMode mode) {
            // Required, but not used in this implementation
        }
    });
    return v;
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
    int position = info.position;
    TaskAdapter adapter = (TaskAdapter)getListAdapter();
    Task task = adapter.getItem(position);

    switch (item.getItemId()) {
    case R.id.menu_item_delete_task:
        TaskLab.get(getActivity()).deleteTask(task);
        adapter.notifyDataSetChanged();
        return true;
    }
    return super.onContextItemSelected(item);
}


@Override
public void onResume() {
    super.onResume();
    ((TaskAdapter)getListAdapter()).notifyDataSetChanged();
}

private class TaskAdapter extends ArrayAdapter<Task> {

    public TaskAdapter(ArrayList<Task> tasks) {
        super(getActivity(), 0, tasks);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // If we weren't given a view, inflate one
        if (convertView == null) {
            convertView = getActivity().getLayoutInflater()
                    .inflate(R.layout.list_item_task, null);
        }

        // Configure the view for this Task
        Task t = getItem(position);

        TextView titleTextView =
                (TextView)convertView.findViewById(R.id.task_list_item_titleTextView);
        titleTextView.setText(t.getTitle());
        TextView dateTextView =
                (TextView)convertView.findViewById(R.id.task_list_item_dateTextView);
        dateTextView.setText(t.getDate().toString());
        CheckBox completedCheckBox =
                (CheckBox)convertView.findViewById(R.id.task_list_item_completedCheckBox);
        completedCheckBox.setChecked(t.isCompleted());
        return convertView;
    }
}
}

编辑:下面是我的TaskLab,用于添加和删除任务。

public class TaskLab {

private static final String TAG = "TaskLab";
private static final String FILENAME = "tasks.json";

private ArrayList<Task> mTasks;
private TaskJSONSerializer mSerializer;

private static TaskLab sTaskLab;
private Context mAppContext;

private TaskLab(Context appContext) {
    mAppContext = appContext;
    mSerializer = new TaskJSONSerializer(mAppContext, FILENAME);

    try {
        mTasks = mSerializer.loadTasks();
    } catch (Exception e) {
        mTasks = new ArrayList<Task>();
        Log.e(TAG, "Error loading tasks: ", e);
    }
}

public static TaskLab get(Context c) {
    if (sTaskLab == null) {
        sTaskLab = new TaskLab(c.getApplicationContext());
    }
    return sTaskLab;
}

public void addTask(Task t) {
        mTasks.add(t);
}

public void deleteTask(Task t) {
    mTasks.remove(t);
}

public boolean saveTasks() {
    try {
        mSerializer.saveTasks(mTasks);
        Log.d(TAG, "Tasks saved to file");
        return true;
    } catch (Exception e) {
        Log.e(TAG, "Error saving tasks: ", e);
        return false;
    }
}

public ArrayList<Task> getTasks() {
    return mTasks;
}

public Task getTask(UUID id) {
    for (Task t : mTasks) {
        if (t.getId().equals(id)) {
            return t;
        }
    } return null;
}
}

0 个答案:

没有答案