[size=large][color=orange][b]布局文件:[/b][/color][/size]
[size=medium]
[color=olive][b]
主程序入口[/b][/color][/size]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity" >
<Spinner
android:id="@+id/myspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
[size=medium]
[color=olive][b]
主程序入口[/b][/color][/size]
package com.sun.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
// 显示的条目内容
private static final String[] m_arr = { "第一组", "第二组", "第三组" };
// 程序入口
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner();
}
// spinner 效果实现
public void spinner(){
Spinner spinner = (Spinner) findViewById(R.id.myspinner);
spinner.setPrompt("请选择颜色"); // 提示标题
// 使用数组适配器进行填充
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinnercolor, android.R.layout.simple_spinner_item);
//ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,m_arr);
// 下拉的样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(0, true); // 默认选择 -- 第一项
spinner.performClick(); //它被定义就调用此视图的OnClickListener(译者注:例如可以在加载时默认弹出下拉列表)
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(MainActivity.this, "选择了:"+getResources().getStringArray(R.array.spinnercolor)[arg2],1000).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}