获取旋转选择器中选定项目的文本?

424

如何获取下拉列表(Spinner)选中项的文本?

当我点击保存按钮时,我需要获取下拉列表(Spinner)中所选项的文本,而不是索引。

13个回答

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

我已经在这里发布了我的问题:https://dev59.com/JFbUa4cB1Zd3GeqPAqh2 - Harsha M V
我使用了这段代码,但结果并非我所需的。在调试模式下,我发现它给出了一个类似于{supliers=VITA}的值,但我只需要"VITA"这个值,有什么想法吗? - Pedro Teran
哇!那是一个简单的解决方案!太棒了! - pumpkee
1
是的,返回值取决于适配器的类型。您的适配器必须是基于游标的,因此它将返回游标。尝试将其强制转换为游标,然后从游标中检索您的值。 - Farhan
@Yar 是的,这个解决方案只适用于字符串基础适配器。当我写下那个答案时,它只是为了处理字符串。现在你有什么问题? - Farhan
显示剩余3条评论

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

6
你应该始终在提出解决方案时包含解释- http://stackoverflow.com/questions/how-to-answer - Michal

38
你必须使用索引和适配器来查找你所拥有的文本。
请参阅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.
    }
}

5
你需要写下 spinner.setOnItemSelectedListener(this); 的翻译。 - whiteLT

17

Spinner返回数组的整数值。您需要根据索引检索字符串值。

Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();

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>

12

设置旋转器适配器后,此代码将有所帮助。

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

        }
    });

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

        }
    });

}

11

简洁版:

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

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

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

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

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

6

使用String.valueOf()可以更加安全地实现,如下所示:

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

当一切失控时,不会导致应用程序崩溃。

它的安全性源于其处理空对象作为参数的能力。文档中说:

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

因此,在例如有一个Spinner的情况下,必须将当前选择的项目转换为String,这里提供了一些保险措施。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接