gpt4 book ai didi

android - 如何为 Spinner 实现 MatrixCursor?

转载 作者:行者123 更新时间:2023-11-29 15:27:45 25 4
gpt4 key购买 nike

我有一个返回 CursorSQLite 查询。我想通过实现 MatrixCursorCursor 添加一些额外的行(以尝试在单击时避免自动选择第一项实际数据)。然后我想将它们映射到 SimpleCursorAdapter。我一直在阅读帖子(和代码),但仍然不清楚如何将其编码为下面列出的现有代码。

    Cursor cursor = myDB.query(DATABASE_TABLE_NAME, resultColumns, whereClause,
whereArgs, null, null, null, null);

// Create Spinner View object from layout resource
Spinner spinner = (Spinner) findViewById(R.id.spinner);

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, // Use a template
// that displays a
// text view
cursor, // Give the cursor to the adapter
new String[] {"ename"}, // Map the NAME column in the
// people database to...
new int[] {android.R.id.text1});

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

最佳答案

如果您想从一个简单的 Cursor 构建一个 MatrixCursor,您必须解析整个初始 Cursor 并附加您需要的行想要:

//...
MatrixCursor mc = new MatrixCursor(resultColumns);
// add extra rows, this will probably not work if you want to insert them
// between the initial cursor rows because of the _id column that need autoincrement values
mc.addRow(new Object[] { new Long(-2), "Extra name1" });
mc.addRow(new Object[] { new Long(-1), "Extra name2" });
// I don't know what your cursor holds, I assumed you have the _id column(long value)
// and a name(String value)
int size = cursor.getCount();
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
mc.addRow(new Object[] {
cursor.getLong(cursor.getColumnIndex(/*the _id column*/)),
cursor.getString(cursor.getColumnIndex(/* the name column(ename?!?)*/)) });
}
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, mc, new String[] {"ename"}, new int[] {android.R.id.text1});
//...

如果您这样做只是为了避免在显示 Spinner 时触发 OnItemSelectedListener,也许您可​​以采用另一种方法。例如在你的听众中:

    //boolean status = true; flag in MyOnItemSelectedListener

@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (status) {
status = false;// this is the first listener trigger so you probably want to ignore it
return;
}
// do stuff here
}

注意:我不知道上面的解决方案有多好。如果您查看这个 Spinner 相关问题,可能有更好的解决方案。

关于android - 如何为 Spinner 实现 MatrixCursor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10168530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com