图像视图 setBackground 未正常运行

Image view setBackground is not acting properly

我有一个 class 使我成为图像按钮。此图像按钮包含一个图像视图、两个文本视图和一个按钮。

我在图像视图中放置了一些宽度,如果我将 xml 一张图像放入背景,它可以正常工作,但是如果我用 java 代码这样做,它就不会有效,它的作用类似于 src 属性。

(图像显示为没有宽度,src 也是如此,而不是 backgorund)。

这是我的 Java 代码:

public class MiBoton extends RelativeLayout{

protected int idImagen;
protected String nomProducte;
protected double preuProducte;
protected String sPreuProducte;
//protected MainActivity maPrincipal;

public MiBoton(Context context, int imgImageResource, String sName, double iPrice){

    super(context);
    this.idImagen = imgImageResource;
    this.nomProducte = sName;
    this.preuProducte = iPrice;
    this.sPreuProducte = Double.toString(iPrice) + " €";


    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.products, this, true);

    ImageView ImageProduct = (ImageView)findViewById(R.id.imatgeproducte);
    TextView ProductName = (TextView)findViewById(R.id.nomproducte);
    ProductName.setTextSize(10);

    TextView ProductPrice = (TextView)findViewById(R.id.preuproducte);


    Drawable new_image= getResources().getDrawable(imgImageResource);
    ImageProduct.setBackground(new_image);

   // ImageProduct.setBackgroundResource(imgImageResource);
    ProductName.setText(sName);
    ProductPrice.setText(sPreuProducte);


    Button btnPedir = (Button)findViewById(R.id.btnPedir);


}


public int getIdImagen() { return idImagen; }
public String getNomProducte() { return nomProducte; }
public double getPreuProducte() { return preuProducte; }

}

这是我的 XML 代码:

<?xml version="1.0" encoding="utf-8"?>
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mi_boton_layout" >

<ImageView
    android:id="@+id/imatgeproducte"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:clickable="true"
    />
<TextView
    android:id="@+id/nomproducte"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/imatgeproducte"
    android:textSize="14sp"
    />
<TextView
    android:id="@+id/preuproducte"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/nomproducte"
    android:textSize="14sp"
    />
<Button
    style="@style/btnStyleGenoa"
    android:layout_width="wrap_content"
    android:layout_height="32dp"
    android:text="Demanar"
    android:textSize="10dp"
    android:id="@+id/btnPedir"
    android:layout_below="@+id/preuproducte"
    />
</RelativeLayout>

尝试使用setImageDrawable(Drawable) instead setBackground(Drawable)

或者你可以直接使用setImageResource(int)和资源id

使用这个方法:

ImageProduct.setImageDrawable(new_image);