将自定义适配器与 CursorLoader 一起使用

Using Custom Adapter with CursorLoader

我正在尝试使用 CursorLoader 从我的 ContentProvider 中获取来自 UI 线程的数据。然后我用它来填充我的列表视图。我之前使用 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() 方法应该 return 一个大于 0 的值。

如何获取 CursorLoader 加载的项目数,以便显示所有元素?目前,我只是 returning 10 让它工作,但这显然不是正确的方法。

这是我的 Fragment class,它实现了 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() 方法中,我需要访问数据以便我可以 select 膨胀哪个布局。我知道我们可以将数据列表传递给 Custom Adapter,但是当数据实际由 CursorLoader?

您可以扩展 CursorAdapter.

而不是扩展 BaseAdapter

调用onLoadFinished时,只需调用swapCursor。您不需要覆盖 getCount()super 已经负责返回正确的值。

我看

SimpleCursorAdapter with ViewBinder set or 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/