0

我正在尝试使用 Android Jellybean (SDK 18) 实现一个简单的 ClipDrawable。我不明白为什么当 ImageView.getDrawable() 返回 Drawable 而不是 BitmapDrawable 时会出现转换错误

这是我在活动的 onCreate() 中的相关代码:

    ImageView image = (ImageView) findViewById(R.id.guage_one);
    ClipDrawable drawable = (ClipDrawable) image.getDrawable();
    drawable.setLevel(10000);

为什么我会为此获得 ClassCastException?我知道 BitmapDrawable 和 ClipDrawable 是 Drawable 的子类,所以你不能将它们相互转换,我知道。但是为什么 image.getDrawable() 返回一个 BitmapDrawable 而不仅仅是一个 drawable 呢?我在文档中遗漏了什么吗?

4

1 回答 1

1

ClipDrawable 不继承 BitmapDrawable。

这是它的继承树:

java.lang.Object

↳ android.graphics.drawable.Drawable

↳ android.graphics.drawable.DrawableWrapper

↳ android.graphics.drawable.ClipDrawable

要将 BitmapDrawable 转换为 ClipDrawable,您可以执行以下操作:

ImageView image = (ImageView) findViewById(R.id.guage_one);
ClipDrawable clipDrawable = new ClipDrawable(image.getDrawable(), Gravity.LEFT, ClipDrawable.HORIZONTAL);
于 2016-11-16T21:52:41.683 回答