Search code examples
javaandroidandroid-imageview

How can I create an image placeholder of an image I am fetching from the web?


I am given the image size, and i want to create a placeholder of that image size's ratio. A simple solid gray color is fine.


Solution

  • You can create one in code like this:

    Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    Paint p = new Paint();
    p.setColor(Color.GRAY);
    p.setStyle(Paint.Style.FILL);
    c.drawRect(0, 0, width, height, p);
    

    but I think it's easier to just create an XML drawable:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid android:color="#FFCCCCCC"/>
    </shape>
    

    You can set that on the ImageView using its R.drawable ID, and then you don't have to worry about your memory use because Android is handling caching and all that.