下拉式選單程式碼
發表人:
Seachaos
積分: 2432
積分: 2432
這是Android下拉式選單的建立方法
於XML敘述檔內需添加以下程式碼
[sea:javaCode]
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></Spinner>
[/sea]
增加選項
[sea:javaCode]
spi=(Spinner)findViewById(R.id.spinner);
List<String> str = new ArrayList<String>();
str.add("Good");
str.add("Nice");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,str);
spi.setAdapter(adapter);
[/sea]
於XML敘述檔內需添加以下程式碼
[sea:javaCode]
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></Spinner>
[/sea]
增加選項
[sea:javaCode]
spi=(Spinner)findViewById(R.id.spinner);
List<String> str = new ArrayList<String>();
str.add("Good");
str.add("Nice");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,str);
spi.setAdapter(adapter);
[/sea]
發表人:
Seachaos
積分: 2432
積分: 2432
增加事件
[sea:javaCode]
spi.setOnItemSelectedListener(spi_onselect);
[/sea]
[sea:javaCode]
public OnItemSelectedListener spi_onselect = new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Value=str.get(arg2);
}
@Override
public void onNothingSelected(AdapterView< ? > arg0) {
// TODO Auto-generated method stub
}
};
[/sea]
Value是目前被選取的值
[sea:javaCode]
spi.setOnItemSelectedListener(spi_onselect);
[/sea]
[sea:javaCode]
public OnItemSelectedListener spi_onselect = new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Value=str.get(arg2);
}
@Override
public void onNothingSelected(AdapterView< ? > arg0) {
// TODO Auto-generated method stub
}
};
[/sea]
Value是目前被選取的值
發表人:
Seachaos
積分: 2432
積分: 2432
另外
可以透過以下程式碼設定目前下拉式選單的外觀
[sea:javaCode]
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
[/sea]
(較為美觀)
可以透過以下程式碼設定目前下拉式選單的外觀
[sea:javaCode]
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
[/sea]
(較為美觀)