coder_For_Life22 coder_For_Life22 -4 years ago 259
Android Question

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?

Answer Source

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);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download