美文网首页
安卓之Spinner

安卓之Spinner

作者: bluewind1230 | 来源:发表于2018-01-18 14:55 被阅读0次
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<String> adapter = new ArrayAdapter<String>(
                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:
<?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"
    android:padding= "20dp"
    tools:context="com.example.spinner.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请选择城市!"
      />

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

</LinearLayout>

item.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:src="@mipmap/ic_launcher"
        android:layout_width="30dp"
        android:layout_height="30dp" />

    <TextView
        android:id="@+id/text"
        android:textSize="20sp"
        android:text="helloworld"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


相关文章

网友评论

      本文标题:安卓之Spinner

      本文链接:https://www.haomeiwen.com/subject/tylwoxtx.html