前兩篇介紹ListView和GridView元件,而這篇再介紹ListView和GridView的好朋友Spinner。Spinner在app常見於填寫資料,由於有選擇的特性能幫助使用者將資料快速填寫完畢。
Spinner在spinner選單裡每一格由一個view組成,view裡有元件或物件(字串)。
相信大家看到第十二篇,底下的程式應該易如反掌,那我們飛過去吧!
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Spinner使用的偵聽方式是setOnItemSelectedListener選擇選項,因此,特別介紹OnItemSelectedListener()要覆寫的方法。
private void setAdapter(){
ArrayAdapter <String> adapter=
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fruit_name);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1);
spinner.setAdapter(adapter);
}
private void setListener() {
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected
(AdapterView<?> adapterView, View view, int position, long l) {
String msg = adapterView.getItemAtPosition(position).toString();
setToast(msg);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
完整程式碼
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
private String[] fruit_name=new String[]{"Apple","Banana","Orange","Grape","Strawberry"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
setAdapter();
setListener();
}
private void setAdapter(){
ArrayAdapter <String> adapter=
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fruit_name);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1);
spinner.setAdapter(adapter);
}
private void findViews () {
spinner=(Spinner)findViewById(R.id.spinner);
}
private void setToast (String text){
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
}
private void setListener() {
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected
(AdapterView<?> adapterView, View view, int position, long l) {
String msg = adapterView.getItemAtPosition(position).toString();
setToast(msg);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
若文章有誤,歡迎大家提出建議。
Thank you for your time.