要实现Spinner中选项的图标与文本并排,可以使用自定义适配器来处理Spinner中每个选项的布局。以下是一个示例代码:
public class CustomAdapter extends ArrayAdapter<String> {
private Context mContext;
private List<String> mOptions;
private List<Integer> mIcons;
public CustomAdapter(Context context, int resource, List<String> objects, List<Integer> icons) {
super(context, resource, objects);
mContext = context;
mOptions = objects;
mIcons = icons;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.spinner_row, parent, false);
TextView textView = row.findViewById(R.id.text_view);
ImageView imageView = row.findViewById(R.id.image_view);
textView.setText(mOptions.get(position));
imageView.setImageResource(mIcons.get(position));
return row;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getView(position, convertView, parent);
}
}
<?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="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"/>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
List<String> options = Arrays.asList("Option 1", "Option 2", "Option 3");
List<Integer> icons = Arrays.asList(R.drawable.ic_option1, R.drawable.ic_option2, R.drawable.ic_option3);
Spinner spinner = findViewById(R.id.spinner);
CustomAdapter adapter = new CustomAdapter(this, R.layout.spinner_row, options, icons);
spinner.setAdapter(adapter);
通过以上步骤,你可以实现Spinner中选项的图标与文本并排显示。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。