Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically create ShapeDrawable

I'm trying to programmatically create a ShapeDrawable but the following code doesn't show anything.

ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
ShapeDrawable badge = new ShapeDrawable (new OvalShape());
badge.setBounds (0, 0, 200, 200);
badge.getPaint().setColor(Color.RED);
ImageView image = new ImageView (context);
image.setImageDrawable (badge);
addView (image);

I can get it working with xml.

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size
        android:width="200px"
        android:height="200px" />
    <solid
        android:color="#F00" />
</shape>

ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
image.setImageResource (R.drawable.badge);
addView (image);

But I would like to create it programmatically. The xml works perfectly so the problem can't be with the ImageView, it must be in creating the ShapeDrawable.

like image 586
RedHatter Avatar asked Jan 06 '16 20:01

RedHatter


1 Answers

Use setIntrinsicWidth and setIntrinsicHeight instead of setBounds to set the width and height.

ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
ShapeDrawable badge = new ShapeDrawable (new OvalShape());
badge.setIntrinsicWidth (200);
badge.setIntrinsicHeight (200);
badge.getPaint().setColor(Color.RED);
image.setImageDrawable (badge);
addView (image);
like image 128
RedHatter Avatar answered Nov 10 '22 15:11

RedHatter