如何在Android中向微调器添加图像

时间:2012-10-31 05:38:05

标签: android android-layout android-spinner

我想在spinner中添加一个图片,我尝试过:

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

但是使用这个代码,旋转器上的向下箭头的标志变得不可见,请告诉我如何解决这个问题!我想完全像在这张图片中那样做

enter image description here

2 个答案:

答案 0 :(得分: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 :(得分: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作为标签