Is it possible to scale drawableleft & drawableright in textview?
I have TextView
with drawableLeft
& drawableRight
in List item.
The problem is, whenever the height of TextView
is larger, drawableLeft
& drawableLeft
didn't automatically scale based on the height of the TextView
.
Is it possible to scale the height of drawableLeft
& drawableRight
in TextView
?
(I was using 9 patch image)
This might help you out. There are two properties scaleX and scaleY
The code below will scale down the image and the text with 30%. Therefore you have to increase the font size with that many "sp", so that when it get re-sized (scaled) it would fit the "sp" you prefer.
Example. If I set the font to 18, then 30% out of 18 is 5.4sp, so roughly, this is the value I am targeting at, because when it gets scaled, it would become 13sp
<TextView
android:textSize="18sp"
android:scaleX="0.7"
android:scaleY="0.7"
The last thing to do is set the CompundDrawable.
tview.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.xxx), null, null, null);
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);
}
});
The only acceptable answer here should be to use an ImageView with the scaleTypes as per usual. Hacky work arounds to scale an image on a TextView that isn't supported by Android seems.. unnecessary. Use the SDK as it was intended.