Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nisrulz/ecf42b8efde0d0a4f7a95d77fb072a3e to your computer and use it in GitHub Desktop.
Save nisrulz/ecf42b8efde0d0a4f7a95d77fb072a3e to your computer and use it in GitHub Desktop.
DrawableLeft to top or DrawableRight to top in TextView multiline.
1. Create Custom TextView.
public class TextViewDrawable extends android.support.v7.widget.AppCompatTextView {
public TextViewDrawable(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
/**
* Support Only Drawable Left or Right
*/
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
int heightTextView = getHeight();
int centerTextView = heightTextView / 2;
Rect r = new Rect();
getLineBounds(0, r);
int lineHeight = r.bottom - r.top +1;
int centerLine = lineHeight / 2;
int topDrawable = centerLine - centerTextView;
Drawable[] compoundDrawables = getCompoundDrawables();
Drawable drawableLeft = compoundDrawables[0];
if (drawableLeft != null) {
drawableLeft.setBounds(0, topDrawable, drawableLeft.getIntrinsicWidth(), drawableLeft.getIntrinsicHeight() + topDrawable);
}
Drawable drawableRight = compoundDrawables[2];
if (drawableRight != null) {
drawableRight.setBounds(0, topDrawable, drawableRight.getIntrinsicWidth(), drawableRight.getIntrinsicHeight() + topDrawable);
}
}
}
2. In xml
<you_package.TextViewDrawable
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:drawableLeft="@drawable/circle_green"
android:text="Hello World!\nHello World!\nHello World!\nHello World!"
/>
3. Change drawable left or right in code
txt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.circle_yellow, 0, 0, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment