第一步:添加一個下拉列表項的list,這裏添加的項就是下拉列表的菜單項java
第二步:爲下拉列表定義一個數組適配器(ArrayAdapter)android
第三步:爲適配器設置下拉列表下拉時的菜單樣式數組
第四步:將適配器添加到下拉列表上app
第五步:爲下拉列表設置各類響應事件ide
在前面第二步與第三步中使用自定義佈局,來實現自定義樣式。佈局
adapter = new ArrayAdapter<String>(this, R.layout.my_item, list); adapter.setDropDownViewResource(R.layout.my_item);
看一個實例:this
1.首先定義Spinnerspa
<!--activity_main.xml--> <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.demo8.MainActivity"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="25sp" android:textColor="#ff0000"/> <Spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/textView"> </Spinner> </RelativeLayout>
2.實現代碼code
package com.example.demo8; 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.TextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private TextView text; private Spinner spinner; private List<String> list; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView) findViewById(R.id.textView); spinner = (Spinner) findViewById(R.id.spinner); //1.設置數據源 list = new ArrayList<String>(); list.add("北京"); list.add("上海"); list.add("廣州"); list.add("深圳"); //2.新建ArrayAdapter(數組適配器) adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); //3.adapter設置一個下拉列表樣式 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //4.加載適配器 spinner.setAdapter(adapter); //5.spinner設置監聽器 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { String cityName = adapter.getItem(i); text.setText(cityName); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } }
運行效果:xml