在Android中,Spinner是一个常用的UI组件,用于展示一组选项供用户选择
下面是一个简单的示例,展示了如何使用自定义数据模型类和适配器类来处理用户自定义数据:
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);
在上面的示例中,我们创建了一个包含三个自定义项的列表,并使用CustomSpinnerAdapter将其设置给Spinner。在getView()方法中,我们自定义了每一项的布局和样式,包括文本和图标。