如何在Android中向下拉列表添加图片

16

我想在下拉框中添加一张图片,我已经尝试过以下方法:

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/myImage" />

但是使用这段代码后,下拉箭头的符号变得不可见,请告诉我如何解决这个问题!!我想做到像这张图片中一样

enter image description here


你想要改变下拉框的背景吗? - Chirag
1
https://dev59.com/-3A65IYBdhLWcg3w1SRC - Niranj Patel
2个回答

16
/res/layout/目录下创建一个row.xml文件,以设置每行的布局。
  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <ImageView
    android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon"/>
    <TextView
    android:id="@+id/weekofday"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>
在Java文件中添加以下代码。
 Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    R.layout.row, R.id.weekofday, YourArrayHere);
  mySpinner.setAdapter(adapter);

1
兄弟,(R.id.spinner) 定义在哪里了? - Siddharth
11
你把图片视图设置在哪里? - Johnny Cheuk
你甚至没有提到Java中的ImageView。 - grantespo

5
在我的情况下,我只是使用了标准布局来创建下拉列表项,并稍微覆盖了ArrayAdapter。
private class PaymentTypeArrayAdapter extends ArrayAdapter<PaymentType> {

    public PaymentTypeArrayAdapter(Context context) {
        super(context, android.R.layout.simple_spinner_item);

        addAll(PaymentType.getPaymentTypes());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView label = (TextView) super.getView(position, convertView, parent);

        PaymentType paymentType = getItem(position);
        label.setText(paymentType.getStringResourceId());
        label.setCompoundDrawablesWithIntrinsicBounds(0, 0, paymentType.
                getImageResourceId(), 0);

        return label;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        TextView label = (TextView) super.getDropDownView(position, convertView, parent);

        PaymentType paymentType = getItem(position);
        label.setText(paymentType.getStringResourceId());
        label.setCompoundDrawablesWithIntrinsicBounds(0, 0, paymentType.
                getImageResourceId(), 0);

        return label;
    }
}

然后为您的下拉列表设置适配器:
mPaymentTypeArrayAdapter = new PaymentTypeArrayAdapter(getContext());
    setAdapter(mPaymentTypeArrayAdapter);

在这种方法中,关键是使用setCompoundDrawablesWithIntrinsicBounds为标签设置图标。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接