如何获得转轮选定项目的文本?
当我点击保存按钮时,我必须在我的旋转器中选择的项目上获得文本。 我需要的是文本,不是索引。
如何获得转轮选定项目的文本?
当我点击保存按钮时,我必须在我的旋转器中选择的项目上获得文本。 我需要的是文本,不是索引。
当前回答
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
其他回答
一行版本:
String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();
更新: 如果使用SDK 26(或更新版本)编译项目,则可以删除强制转换。
String text = findViewById(R.id.spinner).getSelectedItem().toString();
Spinner返回数组的整数值。必须根据索引检索字符串值。
Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
对于那些基于HashMap的旋转器:
((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
如果你在一个片段,一个适配器或一个类,而不是主活动,使用这个:
((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
这只是为了指导;你应该在onClick方法之前找到视图的id。