初识Spinner

Spinner是个下拉列表框,与listview一样,也是adapterView的一个间接子类,是一个显示数据的窗口。

 

 <Spinner

            android:id="@+id/spinner1"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:entries="@array/spinner_name"

            android:prompt="@string/hello_world" />

为Spinner设定数据来源

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string-array name="spinner_name">

        <item>Mercury</item>

        <item>Venus</item>

        <item>Earth</item>

        <item>Mars</item>

        <item>Jupiter</item>

        <item>Saturn</item>

        <item>Uranus</item>

        <item>Neptune</item>

    </string-array>

</resources>

为Spinner设置adapter并添加事件响应

 1     public void showSpinner() {

 2         Spinner spinner = (Spinner) findViewById(R.id.spinner2);

 3         //The simple_spinner_item layout is provided by the platform and is the default layout you should use unless you'd like to define your own layout for the spinner's appearance.

         SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(FormActivity.this, R.array.spinner_name,android.R.layout.simple_spinner_item); 8         

        // Specify the layout to use when the list of choices appears | Sets the layout resource to create the drop down views.
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

 

 9         spinner.setAdapter(spinnerAdapter);

10         spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

19 

20             @Override

21             public void onItemSelected(AdapterView<?> parent, View view,

22                     int position, long id) {

23                 // TODO Auto-generated method stub

24 

25                 Log.i(TAG,

26                         "showSpinner : onItemSelected "

27                                 + ((TextView) view).getText() + ":position "

28                                 + id);

29             }

30 

31             @Override

32             public void onNothingSelected(AdapterView<?> parent) {

33                 // TODO Auto-generated method stub

34                 Log.i(TAG, "showSpinner : onNothingSelected ");

35             }

36         });

37 

38     }

 

你可能感兴趣的:(Spinner)