无法读取android微调器值

时间:2014-02-12 19:09:21

标签: android spinner

我是Android开发新手,只是尝试各种示例来熟悉。 我无法从微调工具中读取和显示值。

检查了Stackoverflow和其他网站的各种示例,但仍然显示空白值。

请告诉我错过的地方。

public void onClick(View view) {
    EditText weight = (EditText)findViewById(R.id.editText1);
    EditText height = (EditText)findViewById(R.id.editText2);

    TextView output = (TextView)findViewById(R.id.textView3);

    Spinner wtype = (Spinner)findViewById(R.id.spinner1);
    Spinner htype = (Spinner)findViewById(R.id.spinner2);

    String w = weight.getText().toString();
    String h = height.getText().toString();
    String s1 = wtype.getSelectedItem().toString();
    String s2 = htype.getSelectedItem().toString();

    output.setText(w+h+s1+s2);
}

在上面的代码中,显示了w和h的值,而s1和s2的值并不适用于所有标准......

这只是一个简单的BMI计算器。 strings.xml包含以下文本。

<string-array name="weight_type">
    <item>kgs</item>
    <item>pounds</item>
</string-array>
<string-array name="height_type">
    <item>metres</item>
    <item>feet</item>
    <item>inches</item>
</string-array>

默认情况下,显示kgs和米。我点击按钮打印2个默认值但没有任何反应.. 我尝试更改下拉值并再次单击该按钮。

仍然没有结果!!!!

尝试来自http://www.mkyong.com/android/android-spinner-drop-down-list-example/的示例 我仍然无法得到结果。唯一的区别是我没有使用TOAST但是试图将输出写入TextView ....

任何人都可以发布工作代码!!!

1 个答案:

答案 0 :(得分:2)

首先,必须在onCreate()方法中声明findViewById。

然后如下所示,在字符串中获取所选项目:

spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1,
                    int pos, long arg3) 
            {
            // TODO Auto-generated method stub
               String s1 = parent.getItemAtPosition(pos).toString();
            }

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

            }
        });

然后在你的onClik方法中,你只需要设置文字:

String w = weight.getText().toString();
String h = height.getText().toString();
String s1 = wtype.getSelectedItem().toString();
String s2 = htype.getSelectedItem().toString(); // Just like S1 as above make another Spinner S2 Listener.

output.setText(w+h+s1+s2);