List<String> list = new ArrayAdapter<String>;
list.add(“test1”);
list.add(“test2”);
ArrayAdapter adpter = new ArrayAdapter(this,R.layout.item,R.id.textId,list);
Spinner.setAdapter(adapter);
Spinner.serPrompt(“标题”); //设置spinner展开后框体的title
第一个参数指上下文对象
第二个参数指定下拉框的样式
第三个参数指定TextView的id,R.id.textid 在R.layout.item中定义
第四个参数提供数据源
package com.example.sp; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; public class MainActivity extends Activity { private Spinner spinner; private Button bt; private List<String> list ; @SuppressWarnings("unused") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner = (Spinner)findViewById(R.id.spinner); bt = (Button)findViewById(R.id.bt); list = new ArrayList<String>(); list.add("text"); list.add("text"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item, R.id.text,list); spinner.setAdapter(adapter); spinner.setPrompt("ceshi"); bt.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub list.add("要添加的数据"); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }Item.xml
<?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" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content"> </TextView> </LinearLayout>
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="fill_parent" > <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/bt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="add" > </Button> </LinearLayout>
为了使样式更好看,可以让设置TextView属性,改变样式