【问题标题】:How to position (select) a spinner on specific item by id with simplecursoradapter?如何使用 simplecursoradapter 通过 id 在特定项目上定位(选择)微调器?
【发布时间】:2014-12-12 07:32:00
【问题描述】:

我正在使用以下代码从我的 SQlite 数据库中填充一些记录:

    DBHelper db = new DBHelper(getBaseContext());
    Cursor cursor_clients = db.select("clients", "_id, name", "ORDER BY name"); // table, fields, filter/order

    String[] columns = new String[] { "name" };
    int[] to = new int[] { android.R.id.text1 };

    SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_clients, columns, to, 0);
    mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
    spnClients.setAdapter(mAdapter);

效果很好,我可以用

spnAcademias.getSelectedItemId();

获取所选记录的_id。我的问题是:如何通过 _id 在此微调器上选择一个项目?

我有我想要的行的 _id,我希望它显示选中的这一行,而不是来自查询的第一行。

【问题讨论】:

    标签: android spinner simplecursoradapter


    【解决方案1】:

    进行更多研究后,我最终找到了解决方案:setSelection on Spinner based on rowId

    我想也许有一个没有循环的本地解决方案,但没有。

    解决方案:

    public void setSpinnerItemById(Spinner spinner, int _id)
    {
        int spinnerCount = spinner.getCount();
        for (int i = 0; i < spinnerCount; i++)
        {
            Cursor value = (Cursor) spinner.getItemAtPosition(i);
            long id = value.getLong(value.getColumnIndex("_id"));
            if (id == _id)
            {
                spinner.setSelection(i);
                break;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您能够同样轻松地获取您要查找的行的文本值,请在此处尝试该解决方案,更具体地说是对其的最高评论:Set selected item of spinner programmatically

      使用以下内容:spinnerObject.setSelection(INDEX_OF_CATEGORY2)。

      ...

      ...我还找到了一种无需遍历适配器即可获取索引的方法。我使用了以下 mySpinner.setSelection(arrayAdapter.getPosition("Category 2"));

      【讨论】:

      • 我似乎是那个解决方案,但我想通过 _id 而不是名称来选择项目。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多