在我的微调器中,我的值是“男”,“女”和“男和女”。如果有人在微调器中单击“男性”,我想检索该值。我现有的使用spinner.getSelectedItem()。toString()的代码提供以下结果:
com.example.kitchen.SpinnerItem@64dd10e
我什至尝试实现.setOnItemSelectedListener(),但这也不起作用。主要活动代码:
public class ManageEventsActivity extends AppCompatActivity {
String stringCreateEventGender;
ArrayList<String> arrayUpcomingEventGender = new ArrayList<>();
ArrayList<SpinnerItem> mGenderList = new ArrayList<>();
SpinnerAdapter genderAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_events);
spinnerCreateEventGender = findViewById(R.id.spinnerCreateEventGender);
initGenderList();
genderAdapter = new SpinnerAdapter(this, mGenderList);
spinnerCreateEventGender.setAdapter(genderAdapter);
}
private void initGenderList() {
mGenderList.add(new SpinnerItem("Male"));
mGenderList.add(new SpinnerItem("Female"));
mGenderList.add(new SpinnerItem("Male and female"));
}
}
Spinner适配器代码:
public class SpinnerAdapter extends ArrayAdapter<SpinnerItem> {
public SpinnerAdapter(Context context, ArrayList<SpinnerItem> genderList) {
super(context, 0, genderList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
private View initView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.spinner_layout, parent, false
);
}
TextView textViewItem = convertView.findViewById(R.id.textViewItem);
SpinnerItem currentItem = getItem(position);
if (currentItem != null) {
textViewItem.setText(currentItem.getItem());
}
return convertView;
}
}
微调项代码:
public class SpinnerItem {
String mItem;
public SpinnerItem(String item) {
mItem = item;
}
public String getItem() {
return mItem;
}
}
您需要将对象强制转换为其原始类型(还要检查其是否不是null
):
@Nullable Object selectedItem = spinner.getSelectedItem();
if (selectedItem != null) { // selectedItem is null if there is nothing selected
String item = ((SpinnerItem) selectedItem).getItem();
}
或者您应该重写toString
方法以返回对象的值:
public class SpinnerItem {
String mItem;
public SpinnerItem(String item) {
mItem = item;
}
public String getItem() {
return mItem;
}
@NonNull
@Override
public String toString() {
return mItem;
}
}
然后spinner.getSelectedItem().toString()
将提供正确的结果:
final String item = spinner.getSelectedItem().toString();