【发布时间】:2015-05-04 20:17:21
【问题描述】:
我正在尝试使用CursorLoader 从 UI 线程的ContentProvider 中获取数据。然后我用它来填充我的列表视图。我之前使用过SimpleCursorAdapter,一切正常。但是现在我想根据数据对列表视图行有不同的视图。
所以我写了一个自定义适配器扩展了基础适配器。
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 10;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Log.d("CustomAdapter", "Check" + i + 1);
if (view == null) {
view = mInflater.inflate(R.layout.listview_text_layout, viewGroup, false);
//if(text) load text view
//else load image view
}
return view;
}
}
但是要显示任何内容,getCount() 方法应该返回一个大于0 的值。
如何获取CursorLoader 加载的项目数以便显示所有元素?目前,我只是返回10 使其工作,但这显然不是正确的方法。
这是我的Fragment 类,它实现了CursorLoader:
public class MessageFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private AbsListView mListView;
private CustomAdapter mAdapter;
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_message, container, false);
getLoaderManager().initLoader(MESSAGES_LOADER, null, this);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(mAdapter);
return view;
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {MessageEntry._ID, MessageEntry.MESSAGE_DATA, MessageEntry.MESSAGE_TIMESTAMP};
switch (i) {
case MESSAGES_LOADER:
return new CursorLoader(
getActivity(),
Uri.parse("content://com.rubberduck.dummy.provider/messages"),
projection,
null,
null,
null
);
default:
return null;
}
}
}
另外,在我的getView() 方法中,我需要访问数据以便选择要膨胀的布局。我知道我们可以将数据列表传递给自定义适配器,但是当数据实际由CursorLoader 加载时,我们该怎么做呢?
【问题讨论】:
标签: android baseadapter custom-adapter android-cursor android-cursorloader