【问题标题】:How to add Image to spinner in Android如何在 Android 中将图像添加到微调器
【发布时间】:2015-07-29 16:29:07
【问题描述】:

我想将图像添加到我尝试过的微调器中:

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

但是使用此代码,微调器上的向下箭头符号变得不可见,请告诉我如何解决该问题!我想完全像这张图片中那样做

【问题讨论】:

标签: android android-layout android-spinner


【解决方案1】:

/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);

【讨论】:

  • 老兄,(R.id.spinner 定义在哪里?
  • 你在哪里设置图像视图?
  • 你甚至没有提到 java 中的图像视图。
【解决方案2】:

在我的例子中,我刚刚对微调器项使用了标准布局,并且只覆盖了一点 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 作为标签

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多