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

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


当前回答

TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);

String subItem = textView.getText().toString();

其他回答

在设置转轮适配器后,这段代码将有所帮助

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getApplicationContext(), "This is " +
                    adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();

            try {
                //Your task here
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

一行版本:

String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();

更新: 如果使用SDK 26(或更新版本)编译项目,则可以删除强制转换。

String text = findViewById(R.id.spinner).getSelectedItem().toString();
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

        }
    });

}
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = 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.
    }
}