标签:
xml:
<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/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:textSize="25sp" />
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
main.java:
package com.example.demo12;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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 ActionBarActivity implements OnItemSelectedListener{
private TextView textView;
private Spinner spinner;
private List<String>list;
private ArrayAdapter<String>adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView) findViewById(R.id.textView);
spinner= (Spinner) findViewById(R.id.spinner);
textView.setText("您选择的城市是北京");
//设置数据源
list=new ArrayList<String>();
list.add("北京");
list.add("上海");
list.add("广州");
list.add("深圳");
//新建ArrayAdapter(数组适配器)
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
//adapter设置一个下拉列表样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//spinner加载适配器
spinner.setAdapter(adapter);
//spinner设置监听器
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String cityName=adapter.getItem(position);
// String city=list.get(position);
textView.setText("您选择的城市是"+cityName);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
标签:
原文地址:http://www.cnblogs.com/daochong/p/4943381.html