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

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


当前回答

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();

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

        }
    });

}
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();