2010年2月25日 星期四

Android学习笔记 - 下拉式选单(Spinner)

1. 透过Spinner物件建立下拉式选单

2. MainActivity.java
package org.me.android_spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        Spinner spinner = (Spinner) findViewById(R.id.spinnner);
        //建立一个ArrayAdapter物件,并放置下拉选单的内容
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,new String[]{"红茶","奶茶","绿茶"});
        //设定下拉选单的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        //设定项目被选取之後的动作
        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView adapterView, View view, int position, long id){
                Toast.makeText(MainActivity.this, "您选择"+adapterView.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
            }
            public void onNothingSelected(AdapterView arg0) {
                Toast.makeText(MainActivity.this, "您没有选择任何项目", Toast.LENGTH_LONG).show();
            }
        });
    }
}


3. main.xml(Layout)

    
    
    
    



4. 下拉式选单画面


沒有留言:

張貼留言