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

发布于 2024-11-03 19:02:33 字数 72 浏览 4 评论 0原文

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

当我单击“保存”按钮时,我必须获取微调器中所选项目的文本。 我需要文本而不是索引。

How to get spinner selected item's text?

I have to get the text on the item selected in my spinner when i click on the save button.
i need the text not the Index.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

潇烟暮雨 2024-11-10 19:02:33
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
孤独难免 2024-11-10 19:02:33
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
屋檐 2024-11-10 19:02:33

您必须使用索引和适配器来查找您拥有的文本请参阅

这个 Spinner 示例< /a>

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.
    }
}

You have to use the index and the Adapter to find out the text you have

See 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.
    }
}
睡美人的小仙女 2024-11-10 19:02:33

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

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

Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.

Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
眼波传意 2024-11-10 19:02:33

使用这个

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>

use this

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>
秋凉 2024-11-10 19:02:33
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_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

        }
    });

}
捶死心动 2024-11-10 19:02:33

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

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

        }
    });

After set the spinner adapter this code will help

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

        }
    });
萌逼全场 2024-11-10 19:02:33

一行版本:

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

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

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

One line version:

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

UPDATE:
You can remove casting if you use SDK 26 (or newer) to compile your project.

String text = findViewById(R.id.spinner).getSelectedItem().toString();
╰ゝ天使的微笑 2024-11-10 19:02:33
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);

String subItem = textView.getText().toString();
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);

String subItem = textView.getText().toString();
灼痛 2024-11-10 19:02:33

它也可以使用 String.valueOf() 就像这样,

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

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

如果参数为null,则字符串等于"null";否则,值为 obj.toString()


因此,有一些保险可以防止 Spinner 的情况,当前所选项目必须转换为 String

It also can be achieved in a little safer way using String.valueOf() like so

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

without crashing the app when all hell breaks loose.
The reason behind its safeness is having the capability of dealing with null objects as the argument. The documentation says

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

So, some insurance there in case of having an empty Spinner for example, which the currently selected item has to be converted to String.

热风软妹 2024-11-10 19:02:33

对于基于 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);
        字符串 ret = null;
        if(cur.moveToFirst()){
            ret = cur.getString(0);
        }
        cur.close();
        返回ret;
    }
    

For spinners based on a CursorAdapter:

  • get the selected item id: spinner.getSelectedItemId()
  • fetch the item name from your database, for example:

    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;
    }
    
饮惑 2024-11-10 19:02:33
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();
—━☆沉默づ 2024-11-10 19:02:33

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

For those have HashMap based spinner :

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

If you are in a Fragment, an Adaptor or a Class other than main activities , use this:

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

It's just for guidance; you should find your view's id before onClick method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文