如何将 Spinner 数据从一个活动传递到另一个活动?

6

这段代码没有从下拉菜单读取值,而是总是只读取第一个值。

btnResult.setOnClickListener(new View.OnClickListener() 
{
    final String USN = spnConversions.getSelectedItem().toString();
    @Override
    public void onClick(View v) 
    {
        Intent i = new Intent(getApplicationContext(), DatabaseResult.class);
        i.putExtra("getData",USN.toString());
        startActivity(i);
    }
});

你想一次传递单个数据还是整个Spinner? - Lucifer
我想一次只传递一个值。就像如果我选择10002,它总是传递第一个值10001。(我按顺序给出了这些数字) - Punith K
3个回答

4
为什么你在Spinner中使用了onClickListener?你应该使用OnItemSelectedListener()来处理Spinner,看下面的示例代码。
public class MySpinnerSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        String selected = parent.getItemAtPosition(pos).toString();
    }

    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}

现在使用以下代码注册监听器:
 spinner.setOnItemSelectedListener(new MySpinnerSelectedListener());

您可以使用以下代码进行传递:

// 发送代码

Intent intent = new Intent(getApplicationContext(), DatabaseResult.class);
intent.putextra("getData",USN.toString());
startActivity(intent);

// 接收代码

String value= getIntent().getStringExtra("getData");

我在另一个活动中也使用了同样的东西。这不是问题,但无论何时从Spinner中选择10002,它都无法获取Spinner的位置值。我需要在第一个活动中添加任何代码吗? - Punith K
谢谢,我做了一些小改动,只是从spinner.onItemSelectedListener()中调用了我的btn.onClickListener(),现在它可以工作了。 - Punith K
感谢您宝贵的时间。 - Punith K

1
尝试这个。
int positionitem = spinner.getSelectedItemPosition();

1
public class SpinnerExample extends Activity
{
     Spinner sp;
     String text ="";
     Button btnResult;

     public void onCreate(Bundle savedInstanceState)
     {
         sp = (Spinner) findViewById(R.id.spinner1);
         sp.setOnItemSelectedListener(new OnItemSelectedListener() {
                   public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3)
                   {
                     this.text = parent.getItemAtPosition(pos).toString();

                   }
                   public void onNothingSelected(AdapterView<?> arg0)
                   {
                            / TODO Auto-generated method stub                  
                   }
          });
          btnResult = (Button) findViewById(R.id.buttonId);
          btnResult.setOnClickListener(new View.OnClickListener() 
          {

                   @Override
                   public void onClick(View v) 
                  {
                        Intent i = new Intent(getApplicationContext(), DatabaseResult.class);
                        i.putExtra("getData",this.text);
                        startActivity(i);
                  }
           });
    }
}

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