天天看點

Android下拉框

Android下拉框

Android下拉框
Android下拉框

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="pw.gutao.android_08_0628.MainActivity">

    <Spinner
        android:id="@+id/s_main_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></Spinner>

</LinearLayout>      

MainActivity.java

package pw.gutao.android_08_0628;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private AutoCompleteTextView autoCompleteTextView;
    private MultiAutoCompleteTextView multiAutoCompleteTextView;
    private Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

              //擷取下拉清單
        spinner = (Spinner) findViewById(R.id.s_main_1);


        //定義數組,儲存省份
        final String[] provinces = {"湖南","湖北","河南","河北","山東","山西"};
        //建立擴充卡
        ArrayAdapter adapters = new ArrayAdapter(this,android.R.layout.simple_list_item_1,provinces);
        //設定擴充卡
        spinner.setAdapter(adapters);
        //擷取目前選中的選項
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,provinces[position]+"省",Toast.LENGTH_SHORT).show();
            }

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

            }
        });
    }
}