Search code examples
androidandroid-imageviewsetbackground

Cannot set the background colour of image view when it don't have an image resource


I want set a background colour to an ImageView, when the imageview has an image resource, it works and i get my background colour but when the image view don't have an image resource, SetBackgroundColor don't work and do nothing, this is my code :

xml Layout :

       <ImageView android:layout_centerHorizontal="true"
        android:id="@+id/favor_item_image" 
        android:layout_alignParentTop="true" android:layout_height="wrap_content"
        android:layout_width="match_parent" android:adjustViewBounds="true"/>

java code :

       ImageView favorImage = (ImageView) MyView.findViewById(R.id.favor_item_image);  
       //favorImage.setImageResource(R.drawable.btndelete);
       favorImage.setBackgroundColor(Color.argb(255,255,0,0));

So, when i comment this line : //favorImage.setImageResource(R.drawable.btndelete); i cannot set the image view background colour , but when i uncomment this line, setBackgroundColor works fine.

any help please. Thanks


Solution

  • The reason you are not seeing anything is because you have the layout_height set to wrap_content. When you do not have an image set on the ImageView wrap_content sets the height to 0. If you want the color to display without an image you will have to set the layout_height to an actual value such as 50dp.