java.lang.Object
? android.view.View
? android.view.ViewGroup
? android.widget.AdapterView<Textends android.widget.Adapter>
? android.widget.AbsSpinner
? android.widget.Spinner
android.widget.Spinner继承了android.view.ViewGroup类。
在Android的UI开发中,Spinner(下拉列表)总是可以用到的,一个简单的自定义Spinner制作我们只需要记住这重要的五步,一个Spinner就可以应用而生了。
(1)新建一个android工程,名称为Spinner。同时建一个Activity,名称为SpinnerActivity。
(2)修改res/layout/main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id = "@+id/TextView_city"
- android:layout_width = "wrap_content"
- android:layout_height = "wrap_content"
- android:text = "所在城市:"
- />
-
- <Spinner
- android:id = "@+id/Spinner_city"
- android:layout_width = "wrap_content"
- android:layout_height ="wrap_content" >
- </Spinner >
- </LinearLayout>
(3)SpinnerActivity.java 代码。
- package cn.com;
-
- import java.util.ArrayList;
- import java.util.List;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.MotionEvent;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.Spinner;
- import android.widget.TextView;
-
- public class SpinnerActivity extends Activity {
-
- private List<String> list = new ArrayList<String>();
- private TextView myTextView;
- private Spinner mySpinner;
- private ArrayAdapter<String> adapter;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- list.add("北京");
- list.add("上海");
- list.add("深圳");
- list.add("福州");
- list.add("厦门");
- myTextView = (TextView)findViewById(R.id.TextView_city);
- mySpinner = (Spinner)findViewById(R.id.Spinner_city);
-
- adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
-
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
-
- mySpinner.setAdapter(adapter);
-
- mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
- public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
-
-
- myTextView.setText("您选择的是:"+ adapter.getItem(arg2));
-
- arg0.setVisibility(View.VISIBLE);
- }
- public void onNothingSelected(AdapterView<?> arg0) {
-
- myTextView.setText("NONE");
- arg0.setVisibility(View.VISIBLE);
- }
- });
-
- mySpinner.setOnTouchListener(new Spinner.OnTouchListener(){
- public boolean onTouch(View v, MotionEvent event) {
-
-
- return false;
- }
- });
-
- mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener(){
- public void onFocusChange(View v, boolean hasFocus) {
-
-
- }
- });
- }
- }
运行结果如下图所示: