407

如何获取微调器选定项目的文本?

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

4

13 回答 13

847
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
于 2011-04-26T08:40:26.063 回答
41
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
于 2012-03-17T15:44:21.777 回答
37

您必须使用索引和适配器来找出您拥有的文本

请参阅此 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.
    }
}
于 2011-04-26T08:35:37.013 回答
17

Spinner 为您返回数组的整数值。您必须根据索引检索字符串值。

Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
于 2011-04-26T08:55:45.877 回答
15

用这个

import java.util.ArrayList;   
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class dynamic_spinner_main extends Activity {

    private Spinner m_myDynamicSpinner;
    private EditText m_addItemText;
    private ArrayAdapter<CharSequence> m_adapterForSpinner;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_spinner);

        ///////////////////////////////////////////////////////////////
        //grab our UI elements so we can manipulate them (in the case of the Spinner)
        //    or add listeners to them (in the case of the buttons)
        m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);        
        m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
        Button addButton = (Button)findViewById(R.id.AddBtn);
        Button clearButton = (Button)findViewById(R.id.ClearBtn);

        ////////////////////////////////////////////////////////////////
        //create an arrayAdapter an assign it to the spinner
        m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
        m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);        
        m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
        m_adapterForSpinner.add("gr");        
        m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // your code here
                Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
                mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
                System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
                startActivity(mIntent);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });
        ////////////////////////////////////////////////////////////////
        //add listener for addButton
        addButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {               
                addNewSpinnerItem();
            }                   
        });

        ////////////////////////////////////////////////////////////////
        //add listener for addButton
        clearButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                clearSpinnerItems();
            }           
        });  
    }

    private void addNewSpinnerItem() {
        CharSequence textHolder = "" + m_addItemText.getText();
        m_adapterForSpinner.add(textHolder);
    }

    private void clearSpinnerItems() {
        m_adapterForSpinner.clear();
        m_adapterForSpinner.add("dummy item");
    }       
}

main_spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <EditText android:layout_height="wrap_content" 
            android:layout_margin="4px" 
            android:id="@+id/newSpinnerItemText" 
            android:layout_width="fill_parent"></EditText>
    <Button android:layout_height="wrap_content" 
            android:id="@+id/AddBtn" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent" 
            android:text="Add To Spinner"></Button>
    <Button android:layout_height="wrap_content" 
            android:id="@+id/ClearBtn" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent" 
            android:text="Clear Spinner Items"></Button>
    <Spinner android:layout_height="wrap_content" 
            android:id="@+id/dynamicSpinner" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent"></Spinner>
</LinearLayout>
于 2011-04-26T09:17:47.420 回答
12
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

        }
    });

}
于 2013-11-21T06:27:43.933 回答
10

一行版本:

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

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

String text = findViewById(R.id.spinner).getSelectedItem().toString();
于 2013-11-07T09:35:38.650 回答
10

设置微调器适配器后,此代码将有所帮助

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) {

        }
    });
于 2018-03-28T20:20:00.080 回答
8
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);

String subItem = textView.getText().toString();
于 2013-04-18T08:09:38.953 回答
5

也可以使用这样的方式以更安全的方式实现String.valueOf()

Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());

当一切都崩溃时,不会导致应用程序崩溃。其安全性背后的原因是具有处理null对象作为参数的能力。文件说

如果参数是null,则字符串等于"null"; 否则,obj.toString()返回 的值。

因此,有一些保险,以防有空 Spinner,例如,当前选定的项目必须转换为String.

于 2018-10-24T16:15:45.147 回答
4

对于基于 CursorAdapter 的微调器:

  • 获取选定的项目 ID:spinner.getSelectedItemId()
  • 从您的数据库中获取项目名称,例如:

    public String getCountryName(int pId){
        Cursor cur = mDb.query(TABLE, new String[]{COL_NAME}, COL_ID+"=?", new String[]{pId+""}, null, null, null);
        String ret = null;
        if(cur.moveToFirst()){
            ret = cur.getString(0);
        }
        cur.close();
        return ret;
    }
    
于 2015-02-04T09:45:55.010 回答
2

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

于 2015-10-22T08:02:37.060 回答
1
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();
于 2015-12-27T11:31:03.037 回答