如何获得转轮选定项目的文本?

当我点击保存按钮时,我必须在我的旋转器中选择的项目上获得文本。 我需要的是文本,不是索引。


当前回答

对于那些基于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。

其他回答

spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {

            String selected_val=spinner_button.getSelectedItem().toString();

            Toast.makeText(getApplicationContext(), selected_val ,
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

}

对于基于CursorAdapter的旋流器:

获得所选项目id: spinner.getSelectedItemId() 从数据库中获取项目名称,例如: getCountryName(int pId){ 游标cur = mDb。查询(表、新String [] {COL_NAME} COL_ID + = ?”,新String [] {pId + " "},空,空,空); 字符串ret = null; 如果(cur.moveToFirst ()) { ret = cur.getString(0); } cur.close (); 返回受潮湿腐烂; }

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的例子

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
      Toast.makeText(parent.getContext()), "The planet is " +
          parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView parent) {
      // Do nothing.
    }
}