问题
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