【问题标题】:Get spinner selected items text?获取微调器选定项目文本?
【发布时间】:2011-08-12 20:50:34
【问题描述】:

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

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

【问题讨论】:

    标签: android android-spinner


    【解决方案1】:
    Spinner spinner = (Spinner)findViewById(R.id.spinner);
    String text = spinner.getSelectedItem().toString();
    

    【讨论】:

    • 已将我的问题发布在这里stackoverflow.com/questions/5818850/…
    • 我使用了代码,但结果不是我在调试模式下所需要的,我发现它给了我一个类似 {suppliers=VITA} 的值。但我只需要值“VITA”有什么想法吗?
    • 哇!这是一个简单的解决方案!太好了!
    • 我试过这个,但我没有得到实际的文本。我得到一个代表游标对象的字符串:android.database.sqlite.SQLiteCursor@410dfae8可能是因为我使用了游标适配器。知道我应该怎么做才能得到正确的字符串吗?
    • 是的,返回值取决于适配器的类型。您的适配器必须是游标基础,因此它将返回游标。尝试将其类型转换为游标,然后从游标中检索您的值。
    【解决方案2】:
    TextView textView = (TextView)mySpinner.getSelectedView();
    String result = textView.getText().toString();
    

    【讨论】:

    【解决方案3】:

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

    this example of 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.
        }
    }
    

    【讨论】:

    • 你还需要spinner.setOnItemSelectedListener(this);
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

      使用这个

      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>
      

      【讨论】:

        【解决方案6】:
        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
        
                }
            });
        
        }
        

        【讨论】:

          【解决方案7】:

          单行版本:

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

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

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

          【讨论】:

            【解决方案8】:

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

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

            【讨论】:

              【解决方案9】:
              TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);
              
              String subItem = textView.getText().toString();
              

              【讨论】:

                【解决方案10】:

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

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

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

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

                因此,如果有一个 empty Spinner,则需要一些保险,例如,当前选定的项目必须转换为 String

                【讨论】:

                  【解决方案11】:

                  对于基于 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;
                    }
                    

                  【讨论】:

                    【解决方案12】:

                    对于那些拥有基于 HashMap 的微调器:

                    ((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
                    

                    如果你在 Fragment、Adapter 或 Class 以外的主要活动中,请使用:

                    ((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
                    

                    仅供参考;您应该在 onClick 方法之前找到您的视图 ID

                    【讨论】:

                      【解决方案13】:
                      Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
                      String text = spinner.getSelectedItem().toString();
                      

                      【讨论】:

                      • 这可以很好地解决问题,但也请提供解释。许多新用户来到 SO 和解释你的代码帮助他们学习如何调整代码来解决他们的问题。
                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2021-12-04
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多