这几天用到了spinner下拉选择,然后看着写的代码听繁琐的,无意中看到这位兄台的博客,感觉很简洁啊,所以就转载来自己看一下,做个学习记录
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="citys">
<item>上海市</item>
<item>厦门市</item>
<item>福建市</item>
<item>北京市</item>
<item>天津市</item>
</string-array>
<string-array name="country">
<item>黄浦区</item>
<item>徐汇区</item>
<item>浦东新区</item>
<item>宝山区</item>
<item>长宁区</item>
</string-array>
</resources>
<pre name="code" class="java">public class SpinnerTest extends Activity implements OnClickListener{
private Button button;
Spinner spinner1,spinner2;
private String text="";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spin_test);
initView();
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
text=(String) spinner1.getSelectedItem();//获取spinner选中的值
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(text.trim().length()>4){
text=text.substring(0, 3);
}
text+=(String) spinner2.getSelectedItem();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void initView() {
// TODO Auto-generated method stub
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(this);
spinner1=(Spinner) findViewById(R.id.spinner1);
spinner2=(Spinner) findViewById(R.id.spinner2);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Toast.makeText(this, text, 0).show();
break;
default:
break;
}
}
}
这是主activity的布局文件
<pre name="code" class="html"><?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:background="@android:color/white"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_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/citys"
/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/country"
/>
</LinearLayout>
<Button
android:id="@+id/button1"
android:layout_marginTop="80dip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取地址" />
</LinearLayout>