【问题标题】:How to fill a Spinner with a Cursor after API level 11?如何在 API 级别 11 之后用光标填充 Spinner?
【发布时间】:2013-05-07 22:36:02
【问题描述】:

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

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

【问题讨论】:

  • 我建议您实现自己的 CursorAdapter 而不是使用 SimpleCursorAdapter。
  • 感谢@DoctororDrive,您的评论很好。你可以考虑神奇地将它变成一个答案,如果你花时间简要描述如何创建一个自定义 CursorAdapter,你至少会赢得我 25 分。

标签: android android-cursor


【解决方案1】:

似乎没有人描述如何使用 API 级别 11 及更高级别进行操作。

showing you a non-deprecated constructor 的文档确实与您尝试使用的文档相同,但带有 int flags 额外参数。如果没有可用的标志值对您有用,则为标志传递 0

【讨论】:

    【解决方案2】:

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

    实现 CursorAdapter 并不比实现任何其他 Adapter 更难。 CursorAdapter 扩展了 BaseAdapter,并且 getItem()、getItemId() 方法已经为您覆盖并返回实际值。 如果您确实支持 pre-Honeycomb,建议使用支持库 (android.support.v4.widget.CursorAdapter) 中的 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);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 2011-11-04
      • 2012-12-23
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多