将微调器数组中的选定值传递给另一个Android类

时间:2015-08-19 17:57:45

标签: java android arrays android-intent spinner

我正在构建一个具有自毁图像的应用程序,我试图将从微调器中选择的值传递给另一个类

final String titles[] = {"1 Second","2 Seconds", "3 Seconds","4 Seconds","5 Seconds","6 Seconds","7 Seconds", "8 seconds, "9 seconds", 10 seconds};
    mSeconds = (Spinner) view.findViewById(R.id.secondsSpinner);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, titles);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

mSeconds.setAdapter(arrayAdapter);
mSeconds.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        int secondsToUse = position + 1;
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // do nothing
    }

});

我的意图方法:

Intent recipientsIntent = new Intent(getActivity(), RecipientsActivity.class);
 recipientsIntent.putExtra("key1", titles);
                      startActivity(recipientsIntent);

如何将选中的值传递给另一个类?我的方法传递整个数组而不是选中的项目。

3 个答案:

答案 0 :(得分:5)

Spinner.getSelectedItem();

将为您提供所选项目。

Intent recipientsIntent = new Intent(getActivity(), RecipientsActivity.class);
                recipientsIntent.putExtra("spinnerItem", Spinner.getSelectedItem());
                startActivity(recipientsIntent);

如果你需要这个lmk背后的额外逻辑..同时Spinner.getSelectedItem()将返回一个对象。你需要把它投射到你期待的任何东西上。一个字符串,例如...... Spinner.getSelectedItem().toString()

在意图中传递int:

Intent recipientsIntent = new Intent(getActivity(), RecipientsActivity.class);
recipientsIntent.putExtra("YOUR_INT_KEY", secondsToUse);
startActivity(recipientsIntent);

你的int不在你的意图中的原因是因为它是onItemSelected()函数的局部变量。使它成为成员变量或将其放在onItemSelected

之外

答案 1 :(得分:1)

bar.cpp

为了阅读:

final String titles[] = {"1 Second","2 Seconds", "3 Seconds","4 Seconds","5 Seconds","6 Seconds","7 Seconds", "8 seconds, "9 seconds", 10 seconds};  
Bundle b=new Bundle();
b.putStringArray(key, titles);
Intent i=new Intent(context, Class);
i.putExtras(b);
startActivity(i);

答案 2 :(得分:1)

这是代码关闭工作

发送:

Intent intentS=new Intent(getActivity(), Main_ExerciseLibrary_Overview_Activity.class);
                    intentS.putExtra("yourInt",Value);
                    startActivity(intentS);

收到:

Bundle b = getIntent().getExtras();
    int myint = b.getInt("yourInt");