以编程方式创建ShapeDrawable

Red*_*ter 12 android drawable

我正在尝试以编程方式创建一个ShapeDrawable,但以下代码不显示任何内容.

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);
Run Code Online (Sandbox Code Playgroud)

我可以使用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);
Run Code Online (Sandbox Code Playgroud)

但我想以编程方式创建它.xml工作得很好所以问题不能用于ImageView,它必须在创建ShapeDrawable.

Red*_*ter 12

使用setIntrinsicWidthsetIntrinsicHeight不是setBounds设置宽度和高度.

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);
Run Code Online (Sandbox Code Playgroud)