我的问题就像this SO question(以及其他类似的问题),但提议的解决方案都不适用于我。所有这些......
String selectedShelf = spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
String selectedShelf = spinner.getSelectedItem().toString();
String selectedShelf = spinner.getItemAtPosition(position).toString();
String selectedShelf = parentView.getItemAtPosition(position).toString();
...导致selectedShelf
的内容为“android.content.ContentResolver$CursorWrapperInner@43bb89b0”。
如何检索所选字符串的值?
这是我的代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View fragmentView = inflater.inflate(R.layout.fragment_browse_spinner, container, false);
Spinner spinner = (Spinner)fragmentView.findViewById(R.id.browseSpinner);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (id != -1L) {
String selectedShelf = ...;
Log.d(LOG_TAG, "selectedShelf: " + selectedShelf);
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
adapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_spinner_item, // This is the layout that will be used for the standard/static part of the spinner. (You can use android.R.layout.simple_list_item_2 if you want two lines to be shown here.)
null,
new String[] {DbContentProvider.KEY_SHELF_NAME, DbContentProvider.KEY_EXTRA_SHELF_INFO},
new int[]{android.R.id.text1, android.R.id.text2},
0
);
// This sets the layout that will be used when the dropdown views are shown. I'm using android.R.layout.simple_list_item_2 so the subtext will also be shown.
adapter.setDropDownViewResource(android.R.layout.simple_list_item_2);
spinner.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.browse_spinner_row_nothing_selected,
getActivity()));
getLoaderManager().initLoader(0, null, this);
return fragmentView;
}
答案 0 :(得分:1)
我已经找到了解决方案:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
TextView selectedShelfTextView = (TextView)selectedItemView.findViewById(android.R.id.text1); // You may need to replace android.R.id.text1 whatever your TextView label id is
String selectedShelf = selectedShelfTextView.getText().toString();