use*_*640 5 android spinner android-widget
我正在使用此示例代码填充Spinner.从数据库中读取数据.选择正确显示 - 在这种情况下,它显示"绿色"和"红色".
Spinner spinnerColor = (Spinner) findViewById(R.id.spinnertProfile);
mProfileDbHelper = new ProfileDbAdapter(this);
mProfileDbHelper.open();
Cursor profilesCursor = mProfileDbHelper.fetchAllProfiles();
startManagingCursor(profilesCursor);
// Create an array to specify the fields we want to display in the list
String[] from = new String[] { ProfileDbAdapter.COL_PROFILE_TITLE };
// and an array of the fields we want to bind those fields to
int[] to = new int[] { R.id.textviewColors };
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter profilesAdapter = new SimpleCursorAdapter(this,
R.layout.profile_color, profilesCursor, from,
to);
spinnerColor.setAdapter(profilesAdapter);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我改为使用不同的布局android.R.layout.simple_spinner_dropdown_item.Spinner Text消失了.
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter profilesAdapter = new SimpleCursorAdapter(this,
R.layout.profile_color, profilesCursor, from,
to);
profilesAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerColor.setAdapter(profilesAdapter);
Run Code Online (Sandbox Code Playgroud)
请参阅下面没有和使用simple_spinner_dropdown_item的快照:

我可能错过什么?
好的,发生的情况是,当您调用时,setDropDownViewResource您将替换之前在构造函数中指定的布局。就你而言R.layout.profile_color。SimpleCursorAdapterextendsResourceCursorAdapter并在构造函数中将两个布局设置为彼此相等。
public ResourceCursorAdapter(Context context, int layout,
Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
mLayout = mDropDownLayout = layout;
mInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Run Code Online (Sandbox Code Playgroud)
setDropDownViewResource当您调用并更改下拉布局时,就会出现问题。将SimpleCursorAdapter继续使用您在构造函数中指定的相同资源 ID 绑定。
您应该做的只是在 的构造函数中指定布局SimpleCursorAdapter。我建议将您的代码更改为如下:
String[] from = new String[] { ProfileDbAdapter.COL_PROFILE_TITLE };
int[] to = new int[] { android.R.id.text1 }; // from simple_spinner_dropdown_item
SimpleCursorAdapter profilesAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_dropdown_item, profilesCursor, from, to);
spinnerColor.setAdapter(profilesAdapter);
Run Code Online (Sandbox Code Playgroud)
以获得您想要的结果。
基本不用这个setDropDownViewResource方法。或者,如果您这样做,并且更改了资源 id 绑定,则必须调用SimpleCursorAdapter#changeCursorAndColumns; 然而,对于您想要实现的简单结果来说,这可能有点过分了。
| 归档时间: |
|
| 查看次数: |
12994 次 |
| 最近记录: |