代码之家  ›  专栏  ›  技术社区  ›  Mika Vatanen

创建一个可绘制的内部类构造函数(并通过扩展?可拉伸类)

  •  1
  • Mika Vatanen  · 技术社区  · 16 年前

    我使用一个类来处理图像的异步加载。在加载过程中,类加载一个colordrawable(稍后将分配给下载的图像)。我希望使用可绘制资源来实现“加载”图像,而不是使用颜色。这怎么可能?在这个可绘制的类“外部”执行它会更容易,但是作为一个限制,我必须在类内部执行它。无法找到如何引用类内资源的方法。

    class myDrawable extends ColorDrawable {
      public myDrawable () {
         super (Color.BLACK);
      }
    }
    

    使用位图绘制是否正确?

    class myDrawable extends BitmapDrawable {
      public myDrawable () {
         super(); // something here to fetch the drawable?
      }
    }
    

    BitmapDrawable构造函数如下:

        public BitmapDrawable(Resources res)
    

    2 回复  |  直到 16 年前
        1
  •  2
  •   Xiaodi Huang    15 年前
    static class HolderDrawable extends BitmapDrawable {
        private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;
    
        public HolderDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
            super(mDefaultBitmap);
            bitmapDownloaderTaskReference = new WeakReference<BitmapDownloaderTask>(
                    bitmapDownloaderTask);
    
        }
    
        public BitmapDownloaderTask getBitmapDownloaderTask() {
            return bitmapDownloaderTaskReference.get();
        }
    
        @Override
        public void draw(Canvas arg0) {
            super.draw(arg0);
        }
    
        @Override
        public int getOpacity() {
            return super.getOpacity(); 
        }
    
        @Override
        public void setAlpha(int alpha) {
            super.setAlpha(alpha);
        }
    
        @Override
        public void setColorFilter(ColorFilter cf) {    
            super.setColorFilter(cf);
        }
    }
    

    您可以从联机下载或从资源中创建mDefaultBitmap。这一步很简单,只要谷歌就行了。我建议您将mDefaultBitmap设置为静态字段,这样就不必每次创建HolderDrawable时都创建它。

        2
  •  0
  •   xandy    16 年前

    Resources ,可从 Context.getResource() ,上下文作为参数传递到自定义视图或活动类本身的构造函数中。