Forked from sonvp/gist:7873060a99895f483ca48fdc030c71ad
Created
October 25, 2022 11:11
-
-
Save nisrulz/ecf42b8efde0d0a4f7a95d77fb072a3e to your computer and use it in GitHub Desktop.
DrawableLeft to top or DrawableRight to top in TextView multiline.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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