Search code examples
androidfresco

Setting TextView's left drawable with Fresco


I've been struggling with this for a while now, using this guide:

http://frescolib.org/docs/writing-custom-views.html

But it suggests writing my own onDraw method, I just want to set TextView's compound drawable. How do I do that?


Solution

  • You don't need to override onDraw, since TextView already does that for you. You can do something like this:

    class MyTextView extends TextView {
      MultiDraweeHolder mMultiDraweeHolder;
    
      // called from constructors
      private void init() {
        mMultiDraweeHolder = new MultiDraweeHolder<GenericDraweeHierarchy>();
        GenericDraweeHierarchyBuilder builder = 
            new GenericDraweeHierarchyBuilder(getResources());
        for (int i = 0; i < 4; i++) {
          GenericDraweeHierarchy hierarchy = builder.reset()
            .set...
            .build();
          mMultiDraweeHolder.add(
              new DraweeHolder<GenericDraweeHierarchy>(hierarchy, getContext()));
      }
    

    To actually set URIs and bounds:

    // build DraweeController as in Fresco docs
    DraweeHolder<GenericDraweeHierarchy> holder = mMultiDraweeHolder.get(i);
    holder.setController(controller);
    holder.getTopLevelDrawable().setBounds(...)
    

    To assign them to your TextView:

    List<Drawable> drawables = new ArrayList<>();
    for (int i = 0; i < 4; i++) {
      drawables.add(mMultiDraweeHolder.get(i).getTopLevelDrawable());
    }
    setCompoundDrawables(
        drawables.get(0), drawables.get(1), drawables.get(2), drawables.get(3));
    

    Your TextView still needs to override the onDetachedFromWindow and other methods as explained in the docs, but you should be able to paste that code as is.