I have a textView in xml here.
<TextView android:id="@+id/bookTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:drawableLeft="@drawable/checkmark" android:gravity="center_vertical" android:textStyle="bold" android:textSize="24dip" android:maxLines="1" android:ellipsize="end"/>
As you can see I set the DrawableLeft in xml.
I would like to change the drawable in code.
Is there anyway to go about doing this? Or setting the drawableLeft in code for the text view?
the best way is to use ConstraintLayout, to make the textview at the center of the layout and the width warp_content(don't use 0dp now) so that the drawable will follow the text.
You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)
set 0 where you don't want images
Example for Drawable on the left:
TextView textView = (TextView) findViewById(R.id.myTxtView); textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.
Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft
From here I see the method setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) can be used to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With