說明:
當選取下拉式選單的Item,以Toast訊息顯示選取的內容。
畫面上的物件:
物件 |
id |
Spinner |
changetype1 |
程式碼:
package com.example.converter;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
private Spinner spinner01; //喧告Spinner物件
private String[] list = {"test1","test2","test3"}; //喧告字串陣列
private ArrayAdapter<String> listAdapter; //喧告listAdapter物件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner01=(Spinner)findViewById(R.id.changetype1); //指向畫面上id為changetype1的Spinner物件
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
spinner01.setAdapter(listAdapter);
//設定項目被選取之後的動作
spinner01.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView adapterView, View view, int position, long id) {
Toast.makeText(MainActivity.this, "你選的是"+spinner01.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView arg0) {
Toast.makeText(MainActivity.this, "您沒有選擇任何項目", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
測試結果:
留言列表