在Android中,Spinner是一個常用的UI組件,用于展示一組選項(xiàng)供用戶選擇
下面是一個簡單的示例,展示了如何使用自定義數(shù)據(jù)模型類和適配器類來處理用戶自定義數(shù)據(jù):
public class CustomItem {
private String title;
private int iconResId;
public CustomItem(String title, int iconResId) {
this.title = title;
this.iconResId = iconResId;
}
public String getTitle() {
return title;
}
public int getIconResId() {
return iconResId;
}
}
public class CustomSpinnerAdapter extends ArrayAdapter<CustomItem> {
private Context context;
private List<CustomItem> items;
public CustomSpinnerAdapter(Context context, List<CustomItem> items) {
super(context, android.R.layout.simple_spinner_item, items);
this.context = context;
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
ImageView imageView = convertView.findViewById(android.R.id.icon);
CustomItem item = items.get(position);
textView.setText(item.getTitle());
imageView.setImageResource(item.getIconResId());
return convertView;
}
}
List<CustomItem> items = new ArrayList<>();
items.add(new CustomItem("Item 1", R.drawable.ic_item1));
items.add(new CustomItem("Item 2", R.drawable.ic_item2));
items.add(new CustomItem("Item 3", R.drawable.ic_item3));
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, items);
spinner.setAdapter(adapter);
在上面的示例中,我們創(chuàng)建了一個包含三個自定義項(xiàng)的列表,并使用CustomSpinnerAdapter將其設(shè)置給Spinner。在getView()方法中,我們自定義了每一項(xiàng)的布局和樣式,包括文本和圖標(biāo)。