Reputation:
I have a class that makes me an imagebutton. This image button contains an image view, tow text view and a button.
I put some width in the image view, and if i put into the xml one image to background, it works properly, but if i do that with java code it don't works, It acts like src atribute.
(the image is being shown as if it has no width, as does src, and not as does backgorund).
This is my Java code:
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; }
}
This is my XML code:
<?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>
Upvotes: 1
Views: 123
Reputation: 32780
Try to use setImageDrawable(Drawable) instead setBackground(Drawable)
Or you can directly use setImageResource(int) with resource id
Upvotes: 1