如何从微调器中检索选定的值并在另一个类中使用它? - Android

时间:2012-08-01 05:16:08

标签: java android spinner

如jalopaba所示,我已经创建了一个新类:How do you get the selected value of a Spinner?

public class MyItemSelectedListener 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 MyOnItemSelectedListener());

但是,我仍然无法使用该选定的字符串来填写同一类中的代码:

textView.setText(selected);

无论如何我是这个Android的新手,所以这个问题可能对你们中的某些人来说太虚伪了

4 个答案:

答案 0 :(得分:2)

在onItemSelected:

中添加setText代码
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    yourTextView.setText(parent.getSelectedItem().toString);
}

答案 1 :(得分:0)

试试这段代码,希望对你有帮助。

final CharSequence[] array_min = {"No 

  Min","100","200","300","400", "500","600","700","800","900","1000",
                  "1100","1200","1300","1400","1500","1600","1700","1800","1900","2000","2500","3000","3500" };

        Spinner s = (Spinner) layout.findViewById(R.id.viewSpin);

        adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, array_min);

        s.setAdapter(adapter);
        s.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View arg1,
                    int arg2, long arg3)
            {
                selItem = parent.getSelectedItem().toString();
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

答案 2 :(得分:0)

使用全局变量..在代码中进行以下更改

选择字符串=&#34;&#34;;

public class MyItemSelectedListener实现OnItemSelectedListener {

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

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

}

textView.setText(选择的);

答案 3 :(得分:0)

在注册微调器之后,您可以在任何操作上获取getSelectedItem()方法中的选定项目,例如ocClick()

 regType = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.regType, android.R.layout.simple_spinner_dropdown_item);
    regType.setAdapter(adapter);

public void onClick(View v){         switch(v.getId()){         案例R.id.btnSave:

        intent.putExtra("regtype",regType.getSelectedItem().toString());
        startActivity(intent);  

            break;}}