Android Studio 開發之 控件開發之Spinner使用示例 -- 升級版

1、layout佈局中添加:

<Spinner
        android:id="@+id/spin_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="50dp"
        android:entries="@array/spin_test"
        android:spinnerMode="dialog"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

2、res/values/目錄下自動生成或者手動生成arrays.xml文件,添加

<string-array name="spin_test">
        <item>北京</item>
        <item>上海</item>
        <item>天津</item>
    </string-array>

3、在MainActivity.java

private Spinner spin_test = null;

spin_test = findViewById(R.id.spin_test);
        spin_test.setAdapter(ArrayAdapter.createFromResource(getApplicationContext(), R.array.spin_test, android.R.layout.simple_spinner_dropdown_item));
        spin_test.setSelection(1);
        spin_test.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                tv_show.setText("i = " + i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

 ----- The End.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章