修改main.xml添加一個Spinner和一個Button.
<?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"
/>
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Read Day of Week"
/>
</LinearLayout>
然後修改主程序:
public class AndroidSpinner extends Activity {
private static final String[] dayOfWeek =
{"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
private ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
Button myButton = (Button)findViewById(R.id.button);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dayOfWeek);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
myButton.setOnClickListener(
new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast
.makeText(AndroidSpinner.this,
(CharSequence) mySpinner.getSelectedItem(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
除此之外, 數組適配器(ArrayAdapter)的內容亦可以使用ArrayAdapter.createFromResource(), 通過XML定義.
沒有留言:
發佈留言