1

我有一个应用程序,它允许用户列出习惯,然后创建目标计时器,以等待他们再次养成该习惯。对于目标创建活动,有许多习惯可供选择。我正在使用以下内容来填充它:

protected void onCreate(Bundle bundle) {
  ⋮
  mHabitSelect = (Spinner) findViewById(R.id.habit);

  String[] queryCols = new String[] { HabitTable.TABLE_HABIT + "." + HabitTable.COLUMN_ID, HabitTable.COLUMN_NAME };
  String[] from = new String[] { HabitTable.COLUMN_NAME };
  int[] to = new int[] { R.id.label };

  Cursor cursor = getContentResolver().query(MyHabitContentProvider.HABITS_URI, queryCols, null, null, null);
  SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.habit_select_row, cursor, from, to, 0);
  mHabitSelect.setAdapter(mAdapter);

  mHabitSelect.setOnItemSelectedListener(this);
}

onItemSelected方法有一个似乎是数据库 id 的 id 参数。

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  long databaseId = id;
}

这给了我保存在数据库中的值,但是我需要一种方法来在加载编辑界面时将微调器设置为从数据库中保存的习惯。

private void fillData(Uri uri) {
  String[] projection = { GoalTable.COLUMN_HABIT_ID, GoalTable.COLUMN_TIME, GoalTable.TABLE_GOAL + "." + GoalTable.COLUMN_DESCRIPTION };
  Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
  if (cursor != null) {
    cursor.moveToFirst();

    int habitId = cursor.getInt(cursor.getColumnIndexOrThrow(GoalTable.COLUMN_HABIT_ID));
    //mHabitSelect.setSelection(habitId);
    ⋮
  }
}

我不必遍历结果来确定哪个数据库 id 位于微调器中的哪个位置,对吗?

4

2 回答 2

0

我有以下情况。我想你可能有同样的情况,你可以做类似的事情:

我有一个包含微调器项目的适配器。区域的适配器。我有 Area 类,我将其对象插入到适配器中。

要获得所选位置的位置,我会这样做:

int index = areasAdapter.items.indexOf(new Area(areaId, areaName));

然后:

spinner.setSelection(index);

在你的情况下:

int index = areasAdapter.items.indexOf(habitId);
spinner.setSelection(index);

或者您拥有的数组列表或您必须在其中存储数据的任何其他东西。可能有类似 indexOf 方法的东西。

于 2013-09-21T01:45:59.387 回答
0

我最终做的是迭代项目以获得位置:

int habitId = cursor.getInt(cursor.getColumnIndexOrThrow(GoalTable.COLUMN_HABIT_ID));
for(int pos = mAdapter.getCount(); pos >= 0; pos--) {
  if(mAdapter.getItemId(pos) == habitId) {
    mHabitSelect.setSelection(pos);
    break;
  }
}
于 2013-09-23T15:14:53.383 回答