我正在尝试使用CursorLoader
从UI线程中获取ContentProvider
的数据。然后,我使用它来填充我的列表视图。我以前在使用SimpleCursorAdapter
,而且一切都很好。但是现在,我希望根据数据的不同视图对列表视图行。
所以我写了自定义适配器扩展 base Adapter 。
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
实际加载数据时,我们该怎么做?
而不是扩展BaseAdapter
,您可以扩展CursorAdapter
。
当onLoadFinished
称为CC_14时,您只需要致电swapCursor
即可。您无需覆盖getCount()
。super
已经在考虑返回正确的值。
SimpleCursorAdapter
设置或 CursorAdapter
足以从我看到的内容中满足您的要求,您不需要扩展BaseAdapter
。
通过LoaderManager
初始化加载程序后,您将通过onLoadFinished()
方法获得结果。
要刷新数据调用swapCursor()
适配器上的方法
还请注意,Activity
在onStart()
中启动了所有注册加载程序,因此启动加载程序的替代位置将在onActivityCreated()
中。
本教程描述了@blackbelt和我正在描述的方式:
http://code.tutsplus.com/tutorials/android-fundamentals-properly-loading-data-mobile-5673
一旦您深入研究装载机,我建议阅读文章:
http://chalup.github.io/blog/2014/06/12/android-loaders/