Spinner

一、spinner控件

Activity代码:

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Spinner sp1=null;

        sp1=(Spinner)findViewById(R.id.sp1);

        //第一个参数是当前上下文

        //第二个是sting.xml中定义的数组

        //第三个指定了spinner的样式是一个布局文件id

        ArrayAdapter<CharSequence> ada=ArrayAdapter.createFromResource(this, R.array.app_items

             android.R.layout.simple_spinner_item);

        //设置每个条目样式

        ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        sp1.setAdapter(ada);

        sp1.setPrompt("国家");

        sp1.setOnItemSelectedListener(new MySelect());

}

//设置监听

    class MySelect implements OnItemSelectedListener{

 

       public void onItemSelected(AdapterView<?> ada, View arg1, int pos,

              long arg3) {

           String str=ada.getItemAtPosition(pos).toString();

           Toast.makeText(SpinnerDemoActivity.this, str, Toast.LENGTH_LONG).show();         

       }

 

       public void onNothingSelected(AdapterView<?> arg0) {

           // TODO Auto-generated method stub

           Toast.makeText(SpinnerDemoActivity.this, "没有选择", Toast.LENGTH_LONG).show();  

       }

    

    }

Strings代码:

<?xmlversion="1.0"encoding="utf-8"?>

<resources>

    <stringname="hello">Hello World, SpinnerDemoActivity!</string>

    <stringname="app_name">SpinnerDemo</string>

    <string-arrayname="app_items">

    <item>中国</item>

    <item>日本</item>

    <item>韩国</item>

    <item>法国</item>

    </string-array>

</resources>

二、使用代码动态添加item

Activity代码:

public class Spinner2Activity extends Activity {

    private Spinner sp=null;

    /** Called when the activity is first created. */

    @Override

    //spinner是一个类似于下拉菜单的控件

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        sp=(Spinner)findViewById(R.id.sp1);

        List<String> list=new ArrayList<String>();

        list.add("中国");

        list.add("法国");

        ArrayAdapter<String> ada=new ArrayAdapter<String>(this,R.layout.item,R.id.textViewId,list);

        //ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        sp.setAdapter(ada);

        sp.setPrompt("国家");

    }

}

posted @ 2011-08-29 23:05  rorshach  阅读(132)  评论(0编辑  收藏  举报