1.目标效果
2.页面布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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"
android:background="@drawable/bg">
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/sipnner"
android:entries="@array/type"/>
<TextView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="这里显示您的选择项"
android:textSize="20dp"/>
</LinearLayout>
这里Spinner控件引用的资源需要在res\values文件中新建资源文件array.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="type">
<item>海贼王 </item>
<item>火影忍者 </item>
<item>死神</item>
<item>叮当猫 </item>
<item>其他 </item>
</string-array>
</resources>
3.事件响应
package com.example.spinnerdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends Activity
{
Spinner spinner=null;
TextView see=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner=(Spinner) findViewById(R.id.sipnner);
see=(TextView) findViewById(R.id.show);
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
//获取数组下标对应的字符串
see.setText("您喜欢的是:"+arg0.getItemAtPosition(arg2));
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
4.运行效果