android - 引用我的自定义 BitmapDrawable 来自 android :src in a resource XML

标签 android bitmap drawable android-resources

我有一个 FrameLayout 如下(两个 android:src 属性均引用 /res/drawable 文件夹中的 .png 文件):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frameLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/ivFrame"
        android:adjustViewBounds="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/frame" />

    <ImageView
        android:id="@+id/ivContent"
        android:adjustViewBounds="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/content" />

</FrameLayout>

现在,我需要对第二个 ImageView (指的是 @drawable/content)进行一些调试。为此,我创建了一个自定义 BitmapDrawable,如下所示:

public class CustomDrawable extends BitmapDrawable {


    public CustomDrawable(Resources res, Bitmap bitmap) {
        super(res, bitmap);
        // TODO Auto-generated constructor stub
    }

    public CustomDrawable(Resources res, InputStream is) {
        super(res, is);
        // TODO Auto-generated constructor stub
    }

    public CustomDrawable(Resources res, String filepath) {
        super(res, filepath);
        // TODO Auto-generated constructor stub
    }

    public CustomDrawable(Resources res) {
        super(res);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        Log.d(Constants.LOG_TAG,"CustomDrawable.onBoundsChanged: "+bounds);
        super.onBoundsChange(bounds);
    }

}

问题:

  1. 如何在 XML 中指定我的 CustomDrawable(并告诉它使用 @drawable/content)
  2. 然后如何告诉布局 XML 中的 ImageView 指向我的 CustomDrawable

最佳答案

您不能在 xml 文件中执行此操作,但可以在代码中执行:

((ImageView) findViewById(R.id.ivContent)).setImageDrawable(new CustomDrawable(...))

关于android - 引用我的自定义 BitmapDrawable 来自 android :src in a resource XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9259798/

相关文章:

android - 无法从 Fragment 中的 ViewModel 观察 LiveData

java.lang.NullPointerException : Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference 异常

java - Android:如何将位图写入内部存储

java - 多个可绘制背景图像以适应屏幕分辨率

java - Android Java SoundPool.setRate 在 Nexus S 上不起作用

android - 通知 setAutoCancel(true) 不起作用

objective-c - 如何将包含核心动画层的 View 渲染到位图?

android - 如果为ldpi、mdpi、hdpi、xhdpi提供了一个drawable资源,这个drawable就不需要为nodpi提供了?

android - 将图像和文本组合成可绘制对象

android - 为特定国家发布 Android 应用