How to add Image to spinner in Android

2020-02-17 10:23发布

I want to add an image to spinner I have tried like:

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

But with this code the sign of down arrow on spinner becomes invisible please tell me how to solve that problem!! I want to do exactly Like in this image

enter image description here

2条回答
迷人小祖宗
2楼-- · 2020-02-17 10:37

Create a row.xml in /res/layout/. To to setup the layout on each row.

  <?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>

and in Java file add this code as

 Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    R.layout.row, R.id.weekofday, YourArrayHere);
  mySpinner.setAdapter(adapter);
查看更多
家丑人穷心不美
3楼-- · 2020-02-17 10:47

In my case I have just used standard layout for spinner items and override just a little the 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;
    }
}

Then set up adapter for your spinner:

mPaymentTypeArrayAdapter = new PaymentTypeArrayAdapter(getContext());
    setAdapter(mPaymentTypeArrayAdapter);

In this approach the key was to use the setCompoundDrawablesWithIntrinsicBounds for the label

查看更多
登录 后发表回答