安卓之Spinner

package com.example.spinner;

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.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //准备数据源
        final String string[] ={"北京","上海","广州"};
        //准备适配器;
        ArrayAdapter adapter = new ArrayAdapter(
                MainActivity.this,
                R.layout.item,
                R.id.text,
                string);

        //3.让控件和适配器进行关联;
        Spinner spinner = findViewById(R.id.spinner);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, string[i], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView adapterView) {

            }
        });
    }
}

activity_main.xml:



    

    



item.xml:




    

    



你可能感兴趣的:(安卓之Spinner)