1. 程式人生 > >安卓下拉框 Spinner

安卓下拉框 Spinner

    <!--普通下拉框-->
      <Spinner
        android:id="@+id/main_sn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></Spinner>
<!--帶圖片下拉框-->
    <Spinner
        android:id="@+id/main_sn2"
        android:layout_width="match_parent"
android:layout_height="wrap_content">
</Spinner>

建立Layout resource 檔案
普通

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:textColor="@color/red"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height
="match_parent">
</TextView>

帶圖片下拉框

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/spn_iv"
        android:layout_width
="100dp" android:layout_height="100dp" />
<TextView android:id="@+id/spn_tv" android:layout_width="100dp" android:layout_height="100dp" /> </LinearLayout>
package com.example.app7;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

public class MainActivity extends AppCompatActivity {
    private List data1;
    private ArrayAdapter adapter;
    private Spinner spinner1;
    private List<Map<String,Object>> data2;
    private Spinner spinner2;
    private SimpleAdapter simpleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        data1=new ArrayList();
        data2=new ArrayList<>();

        spinner1=findViewById(R.id.main_sn1);
        spinner2=findViewById(R.id.main_sn2);
//        1.獲得資料
        data1 =new String[]{ "憤怒的小鳥", "湯姆貓", "落湯雞", "牛牛", "哈巴狗", "神龍", "烤鴨",
                "小象", "美人魚", "九尾狐" };

        List<Book> list = new BookDAO().list();
        Map<String, Object> map;
        for (Book book:list) {
            data1.add(new option(book.getId()+"",book.getName()));
            map=new HashMap<>();
            map.put("name", book.getName());
            map.put("image", book.getImage());
            data2.add(map);
        }



//        2、初始化介面卡


        adapter =new ArrayAdapter(this,R.layout.main_act1,data2);

        simpleAdapter =new SimpleAdapter(this,data3,R.layout.spn_spn2,new String[]{"name","image"},new int[]{R.id.spn_tv,R.id.spn_iv});

//        3.繫結介面卡
        spinner1.setAdapter(adapter);
        spinner2.setAdapter(simpleAdapter);


    }
}