アダプタのgetView()メソッドをオーバーライドし、レイアウトパラメータをテキストビューに設定してコンテンツをラップする必要があります。スピナーは、選択したアイテムのサイズを自動的に変更します。
ArrayAdapterから拡張するカスタムアダプタを作成しました。
public class CustomAdapter extends ArrayAdapter<String> {
その後、getView()メソッドをオーバーライドして、現在のビューのLayoutParamsを変更します。
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View view = convertView;
if (null == view) {
view = LayoutInflater.from(this.getContext())
.inflate(android.R.layout.simple_list_item1, null);
((TextView) view).setText(getItem(position));
}
final LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
view.setLayoutParams(params);
return view;
}
アクティビティで、アダプタインスタンスを作成し、スピナーを設定します。
List<String> stringList = new ArrayList<String>();
stringList.add("test1");
stringList.add("test12");
stringList.add("test123");
stringList.add("test1234");
final SpinnerAdapter adapter = new CustomAdapter(this.getContext(),
android.R.layout.simple_list_item1,
android.R.id.text1,
stringList);
mySpinner.setAdapter(adapter);
リストから何かを選択すると、スピナーはビューを再作成し、選択したアイテムを最初の位置に並べ替えて、コンテンツのサイズに合わせてサイズを変更します。