Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set left drawable in a TextView

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?

like image 428
coder_For_Life22 Avatar asked Aug 03 '11 19:08

coder_For_Life22


People also ask

How do you center a drawable in Textview?

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.


2 Answers

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

like image 72
BrainCrash Avatar answered Sep 19 '22 23:09

BrainCrash


From here I see the method setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) can be used to do this.

like image 36
Jack Avatar answered Sep 22 '22 23:09

Jack