(一)
1.效果图:ArrayAdapter可以不用设置
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
2.activity_main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 tools:context="com.example.app3.MainActivity"> 8 9 <Spinner 10 android:id="@+id/spin" 11 android:background="@color/colorAccent" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:dropDownVerticalOffset="100dp" 15 android:dropDownHorizontalOffset="100dp" 16 /> 17 </LinearLayout>
3.MianActivity.java
1 package com.example.app3; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.view.View; 6 import android.widget.Adapter; 7 import android.widget.AdapterView; 8 import android.widget.ArrayAdapter; 9 import android.widget.Spinner; 10 import android.widget.Toast; 11 12 import java.util.ArrayList; 13 import java.util.List; 14 15 public class MainActivity extends AppCompatActivity { 16 private Spinner spinner; 17 private List<String> list; 18 private ArrayAdapter arrayAdapter; 19 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 26 spinner=(Spinner)findViewById(R.id.spin); 27 28 //新建适配器 29 list = new ArrayList<>(); 30 for (int i=0;i<3;i++){ 31 list.add("spinner"+i); 32 } 33 arrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item,list); 34 35 spinner.setAdapter(arrayAdapter); 36 37 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 38 @Override 39 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 40 Toast.makeText(MainActivity.this,list.get(position),Toast.LENGTH_SHORT).show(); 41 } 42 43 @Override 44 public void onNothingSelected(AdapterView<?> parent) { 45 46 } 47 }); 48 } 49 }
(二)用简单适配器的时候必须设置