How to fill a Spinner with a Cursor after API level 11?

僤鯓⒐⒋嵵緔 提交于 2019-12-08 06:15:25

问题


I have found lots of answers on SO and other websites about how to fill a Spinner with a Cursor, but all of them use the deprectated SimpleCursorAdapter(Context, int, String[], int[]) constructor to do that. No one seems to describe how to do it with API level 11 and above.

The API tells me to use the LoaderManager, but I'm not sure about how to use that.


回答1:


I would suggest implementing your own CursorAdapter instead of using SimpleCursorAdapter.

Implementing a CursorAdapter is no harder than implementing any other Adapter. CursorAdapter extends BaseAdapter, and getItem(), getItemId() methods are already overriden for you and return the real values. It's recommended to use the CursorAdapter from support library (android.support.v4.widget.CursorAdapter) if you do support pre-Honeycomb. If you are only after 11, just use the android.widget.CursorAdapter Mind that you don't need to call notifyDataSetChanged() when you call swapCursor(newCursor);

import android.widget.CursorAdapter;

public final class CustomAdapter
        extends CursorAdapter
{

    public CustomAdapter(Context context)
    {
        super(context, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    }


    // here is where you bind the data for the view returned in newView()
    @Override
    public void bindView(View view, Context arg1, Cursor c)
    {

        //just get the data directly from the cursor to your Views.

        final TextView address = (TextView) view
                .findViewById(R.id.list_item_address);
        final TextView title = (TextView) view
                .findViewById(R.id.list_item_title);

        final String name = c.getString(c.getColumnIndex("name"));
        final String addressValue = c.getString(c.getColumnIndex("address"));

        title.setText(name);
        address.setText(addressValue);
    }

    // here is where you create a new view
    @Override
    public View newView(Context arg0, Cursor arg1, ViewGroup arg2)
    {
        return inflater.inflate(R.layout.list_item, null);
    }

}



回答2:


No one seems to describe how to do it with API level 11 and above.

The documentation does, by showing you a non-deprecated constructor that is the same as the one you are trying to use, with a int flags extra parameter. Pass 0 for the flags if none of the available flag values are useful to you.



来源:https://stackoverflow.com/questions/16414644/how-to-fill-a-spinner-with-a-cursor-after-api-level-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!