在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應該顯示每個項目的圖像和文本。記住根據您的需求調整代碼。