xml에서 'android:prompt' 와 'android:entries'속성을 이용하여 구현하는 방식과
자바코드에 createFromResource(context, textArrayResId, textViewResId); method 와 setDropDownViewResource(resource); method를 이용하여 setAdaptger(adapter); 하는 방식이 입니다.
개인적으로는 2번째 방식을 많이 사용하지만 2가지 경우에 대해 설명 드리겠습니다.
설명에 앞서 공통으로 사용 할 Listener 코드입니다. Spinner에서는 onSelectedListener를 사용합니다.
private class MyOnItemSelectedListener implements OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(),
"The planet is " + parent.getItemIdAtPosition(pos),
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView parent) {
// TODO Auto-generated method stub
// Do nothing
}
}
1. xml 방식.
<?xml version=”1.0” encoding=”utf-8”?>
<linearlayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >
<Spinner
android:id=”@+id/spinner1”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:prompt=”@string/planet_prompt”
android:entries=”@array/planets_array”/>
</LinearLayout>
android:prompt="@string/planet_prompt" 속성은 Spinner에 표기되는 제목 속성이며,
android:entries="@array/planets_array" 속성은 스피너에 출력되는 자료를 연결 하는 속성입니다.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
2.JAVA코드 방식.
<?xml version=”1.0” encoding=”utf-8”?>
<linearlayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >
<Spinner
android:id=”@+id/spinner1”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”/>
</LinearLayout>
'android:prompt' 속성과 'android:entries'을 xml에서 제외 시켜 주고 JAVA 코드에서 작성하면 된다.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner.setPrompt(getResources().getString(R.string.planet_prompt));
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.planets_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
Spinner 구현이 어려운 내용은 없으나 테스트 하다가 의문점은 android:prompt 속성이 갤럭시 노트2에서는 적용이 안되는 점이였습니다. 여러 Device를 테스트 해 보지는 못했지만 아마 아이스크림 샌드위치로 넘어오면서 사라진게 아니면 Device를 타는 것 같습니다.
댓글 없음:
댓글 쓰기