【发布时间】:2018-10-07 15:51:34
【问题描述】:
我的应用程序中的三个片段 Fragment1、Fragment2、Fragment3 使用单个自定义 CursorAdapter 类 TaskCursorAdapter 在列表视图中显示单个表的内容。这是课程:
public class TaskCursorAdapter extends CursorAdapter {
public TaskCursorAdapter(Context context, Cursor c) {
super(context, c, 0 /* flags */);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item_task, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView titleTextView = (TextView) view.findViewById(R.id.task_title);
TextView detailsTextView = (TextView) view.findViewById(R.id.task_details);
int titleColumnIndex = cursor.getColumnIndex(TaskEntry.COLUMN_TASK_TITLE);
int detailsColumnIndex = cursor.getColumnIndex(TaskEntry.COLUMN_TASK_DETAILS);
String taskTitle = cursor.getString(titleColumnIndex);
String taskDetails = cursor.getString(detailsColumnIndex);
if (TextUtils.isEmpty(taskDetails)) {
taskDetails = context.getString(R.string.unknown_task);
}
titleTextView.setText(taskTitle);
detailsTextView.setText(taskDetails);
}
}
该表在 Contract 类中指定为 TaskEntry。它还有另一个名为 TaskEntry.COLUMN_TASK_STATUS="status" 的列。可能的值是 0、1 或 2。目前,所有项目都显示在两个片段中。但是,我想让它只在 Fragment1 中显示 status=0 的行,在 Fragment2 中显示 status=1 的行,在 Fragment3 中显示 status=2 的行。
我在 bindView 方法中尝试了以下方法:
int taskStatus = Integer.parseInt(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_STATUS)));
if(taskStatus==0) { //code in bindView }
这导致在所有片段中仅显示状态 = 0 的项目,但它留下了一个空的膨胀视图来代替状态不是 0 的项目。 此外,我找不到传递信息以使其特定于 Fragment1 的方法。
我应该如何根据状态值和片段有条件地显示行?
编辑: 什么有效:
我没有在 TaskCursorAdapter 中尝试这个,而是在 onCreateLoader 方法中使用条件查询,如下所示:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String selectionArgs[] = {"<status>"};
String[] projection = {
TaskEntry._ID,
TaskEntry.COLUMN_TASK_TITLE,
TaskEntry.COLUMN_TASK_DETAILS};
return new CursorLoader(this.getActivity(), TaskEntry.CONTENT_URI, projection,
TaskEntry.COLUMN_TASK_STATUS + " = ?", selectionArgs, null);
}
【问题讨论】:
标签: android android-fragments android-cursoradapter