android Spinner(下拉菜单)的应用举例2---动态实现

来源:互联网 发布:张建伟 人工智能 编辑:程序博客网 时间:2024/04/28 20:42

AppMain.java

package lxy.litsoft;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.Toast;import android.widget.AdapterView.OnItemSelectedListener;public class AppMain extends Activity {Spinner s;//声明一个Spinner对象List<String> list;ArrayAdapter adapter;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);            //创建一个list存放Spinner要显示的item        list = new ArrayList<String>();        list.add("Beijing");        list.add("Xiaozhuang");                //Adapter为Spinner提供数据        adapter = new ArrayAdapter(this,R.layout.item,R.id.textViewForItem,list);                s = (Spinner)findViewById(R.id.spinner);//得到Spinner的对象        s.setAdapter(adapter);//添加适配器        s.setOnItemSelectedListener(new SpinnerListener());//绑定监听器        s.setPrompt("地点");//设置选项列表的title           }        class SpinnerListener implements OnItemSelectedListener{public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {String selected = arg0.getItemAtPosition(arg2).toString();Toast.makeText(AppMain.this, "what you selected is :"+selected, Toast.LENGTH_LONG).show();Log.d("test", "what you selected is :"+selected);}public void onNothingSelected(AdapterView<?> arg0) {Toast.makeText(AppMain.this, "you have selected nothing", Toast.LENGTH_LONG).show();Log.d("test", "you have selected nothing");}        }}

item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView    android:id="@+id/textViewForItem"    android:layout_width="fill_parent"    android:layout_height="wrap_content"></TextView></LinearLayout>

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    /><Spinner    android:id="@+id/spinner"    android:layout_width="fill_parent"     android:layout_height="wrap_content"></Spinner></LinearLayout>



原创粉丝点击