Android Development: Basic Control Spinner Dropdown List Control

                                                          

Spinner provides a quick way to select a value from a data set. By default, Spinner displays the currently selected value. Clicking on Spinner will bring up a drop down menu containing all the optional values from which a new value can be selected for Spinner.

The figure above shows the common style of Spinner. In this article I will discuss 1.Spinner's basic usage 2. Setting Spinner's Adapter (arrayadapter and custom BaseAdapter)3.Spinner's menu display 4.Spinner's xml properties

The Simplest Spinner
Adding Spinner Control to Layout File

 <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
 
        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:entries="@array/languages"
          />
    </LinearLayout


Android:entries="@array/languages" indicates that Spinner's data set is obtained from the resource array languages, which is defined in values/arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="languages">
        <item>c language</item>
        <item>java </item>
        <item>php</item>
        <item>xml</item>
        <item>html</item>
    </string-array>
</resources>


If you don't need to respond to Spinner's selection events, a complete Spinner usage process is over.

Of course, in general, we need to respond to Spinner selection events, which can be achieved through OnItemSelectedListener's callback method.

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner spinner = (Spinner) findViewById(R.id.spinner1);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, 
                    int pos, long id) {
 
                String[] languages = getResources().getStringArray(R.array.languages);
                Toast.makeText(MainActivity.this, "What you clicked on was:"+languages[pos], 2000).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
    }
 
}

 


Link to the original text: https://blog.csdn.net/qq_32059827/article/details/53106821

Keywords: Android xml encoding Java

Added by ccbayer on Sun, 06 Oct 2019 21:33:49 +0300