在Android的Spinner Adapter中显示图片,您需要创建一个自定义的Adapter,通常是通过扩展BaseAdapter或ArrayAdapter
<?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"
android:padding="8dp">
<ImageView
android:id="@+id/image"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="Item Text"
android:textSize="16sp" />
</LinearLayout>
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class CustomSpinnerAdapter extends ArrayAdapter<Item> {
public CustomSpinnerAdapter(Context context, List<Item> items) {
super(context, 0, items);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_item, parent, false);
ImageView imageView = convertView.findViewById(R.id.image);
TextView textView = convertView.findViewById(R.id.text);
Item item = getItem(position);
if (item != null) {
imageView.setImageResource(item.getImage());
textView.setText(item.getText());
}
return convertView;
}
}
注意:这里的Item
类应该包含图片和文本。
// 假设您已经创建了一个名为items的Item列表。
List<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.image1, "Item 1"));
items.add(new Item(R.drawable.image2, "Item 2"));
// ...添加更多项
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, items);
Spinner spinner = findViewById(R.id.spinner);
spinner.setAdapter(adapter);
现在,您的Spinner应该显示每个项目的图像和文本。记住根据您的需求调整代码。