如何在API级别11之后用游标填充Spinner



我在SO和其他网站上找到了很多关于如何用Cursor填充Spinner的答案,但他们都使用弃用的SimpleCursorAdapter(Context, int, String[], int[])构造函数来做到这一点。似乎没有人描述如何在API级别11及以上的情况下实现它。

API告诉我使用LoaderManager,但我不确定如何使用。

似乎没有人描述如何在API级别11及以上的情况下做到这一点。

文档通过向您展示一个未弃用的构造函数(与您尝试使用的构造函数相同),并带有int flags额外参数来实现此功能。如果没有可用的标志值对您有用,则传递0作为标志。

我建议实现您自己的CursorAdapter而不是使用SimpleCursorAdapter。

实现一个CursorAdapter并不比实现任何其他Adapter更难。CursorAdapter扩展了BaseAdapter, getItem()、getItemId()方法已经为您覆盖并返回实际值。如果您确实支持pre-Honeycomb,建议使用支持库中的CursorAdapter (android.support.v4.widget.CursorAdapter)。如果你只是在11之后,只需使用android.widget.CursorAdapter注意,当你调用swapCursor(newCursor);

时,你不需要调用notifyDataSetChanged()
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);
    }
}

最新更新