本篇承接第四十话第四十话《Spinner》
参考博客:http://blog.csdn.net/yayun0516
进入正题:
Strings加入第一级数据:
<string-array name="province">
<item >水果</item>
<item >职位</item>
<item >动物</item>
</string-array>
来个布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/province"/> <Spinner
android:id="@+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout> <TextView
android:text="nihao"
android:id="@+id/text"
android:textColor="#00ff00"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView> </LinearLayout>
总共两级菜单,一个文本。
主活动代码如下:
package com.ydl.test;
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.TextView; public class MainActivity extends Activity {
private Spinner spinner1;
private Spinner spinner2;
private TextView textView;
private String string1;
private String[][] dataStrings = { { "苹果", "香蕉", "梨子", "菠萝", "草莓", },
{ "教师", "工人", "程序员", }, { "老虎", "狮子", "大象", }, };
private ArrayAdapter<CharSequence> adapter = null; public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // 生命周期方法
super.setContentView(R.layout.activity_main); // 设置要使用的布局管理器
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
textView = (TextView) findViewById(R.id.text);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
adapter = new ArrayAdapter<CharSequence>(MainActivity.this,
android.R.layout.simple_spinner_item,
dataStrings[position]);//根据position确定第二个spinner中要填充的数据
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//设置点击下拉窗体的显示样式
//给spinner2设置adapter
spinner2.setAdapter(adapter);
//parent指的是 spinner1
string1 = parent.getItemAtPosition(position).toString();// 获取当前显示省份
} public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub }
}); spinner2.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
//parent指的是 spinner2
String string2 = parent.getItemAtPosition(position).toString();// 获取当前显示省份
textView.setText(string1 +" : "+ string2); } public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub }
}); }
}
运行程序如下:
连通完成~
喜欢的朋友可以关注我哦,不定期更新简单有趣的Android小文~