Is it possible to scale drawableleft & drawableright in textview?

前端 未结 8 2206
悲&欢浪女
悲&欢浪女 2020-12-14 05:53

I have TextView with drawableLeft & drawableRight in List item. The problem is, whenever the height of TextView is l

8条回答
  •  天涯浪人
    2020-12-14 06:01

    I solved an equivalent usecase by introducing a ScaleDrawable and overriding its .getIntrisicHeight() so that it is at least the TextView height. The TextView.addOnLayoutChangeListener part, required to rebind the Drawable on a TextView size change works with API11+

    Drawable underlyingDrawable = 
            new BitmapDrawable(context.getResources(), result);
    
    // Wrap to scale up to the TextView height
    final ScaleDrawable scaledLeft = 
            new ScaleDrawable(underlyingDrawable, Gravity.CENTER, 1F, 1F) {
        // Give this drawable a height being at
        // least the TextView height. It will be
        // used by
        // TextView.setCompoundDrawablesWithIntrinsicBounds
        public int getIntrinsicHeight() {
            return Math.max(super.getIntrinsicHeight(), 
                            competitorView.getHeight());
        };
    };
    
    // Set explicitly level else the default value
    // (0) will prevent .draw to effectively draw
    // the underlying Drawable
    scaledLeft.setLevel(10000);
    
    // Set the drawable as a component of the
    // TextView
    competitorView.setCompoundDrawablesWithIntrinsicBounds(
            scaledLeft, null, null, null);
    
    // If the text is changed, we need to
    // re-register the Drawable to recompute the
    // bounds given the new TextView height
    competitorView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
    
        @Override
        public void onLayoutChange(View v, int left, int top, int right, 
                int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            competitorView.setCompoundDrawablesWithIntrinsicBounds(scaledLeft, null, null, null);
        }
    });
    

提交回复
热议问题