android Spinner方法

时间:2011-12-19 09:18:30

标签: android spinner

我试图在我的微调器教程上工作,但它似乎没有显示标题。任何人都可以指导我可能忽略哪一部分?

public class HelloSpinnerActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        spinnertest = (Spinner) findViewById(R.id.Spinner01);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.Planets, android.R.layout.simple_spinner_item);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnertest.setAdapter(adapter);
        spinnertest.setOnItemSelectedListener(new MyOnItemSelectedListener());
    }
    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.
        }
    }
}

main.xml中

<Spinner 
    android:id="@+id/Spinner01"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:prompt = "@string/planet_prompt"
    android:entries ="@array/Planets">
</Spinner>

的strings.xml

<string name="app_name">Spinner</string>
 <string name="planet_prompt"> Select a planet </string>
<string-array name="Planets">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
    <item>Pluto</item>
</string-array>

2 个答案:

答案 0 :(得分:0)

不太确定这是否可行解决方案会有所帮助(您可能有特别的理由以自己的方式尝试),但过去我刚刚将提示文本添加到Spinner字符串数组的顶部(at位置0),然后它默认显示在小部件中。然后,在'onItemSelected'中,如果pos == 0,我会忽略任何内容。

答案 1 :(得分:0)

我不确切地知道“header”的含义,但是教程会在main.xml中的T​​extView中显示一个提示,但你没有显示:

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dip"
    android:text="@string/planet_prompt" />

此外,由于您在XML中初始化微调器,因此无需在代码中执行此操作。试试这个:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}