null pointer
null pointer

Reputation: 5914

set android textView drawableEnd programmatically

How to set the android:drawableEnd of TextView from the java code? the setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int) can be used on left, right, top and bottom only. how to set drawableEnd?

Upvotes: 12

Views: 11399

Answers (3)

Priyanka Thakkar
Priyanka Thakkar

Reputation: 304

To set drawableend programatically,Use below code. Worked for me.

   rowTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_call_black_24dp, 0);

Upvotes: 20

If you use kotlin, I can advise the following extensions for EditText interaction with Drawables.

var EditText.drawableStart: Drawable?
    get() = compoundDrawablesRelative?.get(0)
    set(value) = setDrawables(start = value)

var EditText.drawableTop: Drawable?
    get() = compoundDrawablesRelative?.get(1)
    set(value) = setDrawables(top = value)

var EditText.drawableEnd: Drawable?
    get() = compoundDrawablesRelative?.get(2)
    set(value) = setDrawables(end = value)

var EditText.drawableBottom: Drawable?
    get() = compoundDrawablesRelative?.get(2)
    set(value) = setDrawables(bottom = value)


fun EditText.setDrawables(
    start: Drawable? = null,
    top: Drawable? = null,
    end: Drawable? = null,
    bottom: Drawable? = null
) = setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom)

After adding these extensions, you can work with Drawables as follows:

drawableEnd = context.getDrawable(R.drawable.ic_close_black)

I think that here it is necessary to use the method 'setCompoundDrawablesRelativeWithIntrinsicBounds'. Because inside the implementation, it sets the values for the variables mDrawableEnd and mDrawableStart. These variables are substituted in left and rigt, if not null, this is seen in the example of such code inside the TextView:

if (mIsRtlCompatibilityMode) {
                // Use "start" drawable as "left" drawable if the "left" drawable was not defined
                if (mDrawableStart != null && mShowing[Drawables.LEFT] == null) {
                    mShowing[Drawables.LEFT] = mDrawableStart;
                    mDrawableSizeLeft = mDrawableSizeStart;
                    mDrawableHeightLeft = mDrawableHeightStart;
                }
                // Use "end" drawable as "right" drawable if the "right" drawable was not defined
                if (mDrawableEnd != null && mShowing[Drawables.RIGHT] == null) {
                    mShowing[Drawables.RIGHT] = mDrawableEnd;
                    mDrawableSizeRight = mDrawableSizeEnd;
                    mDrawableHeightRight = mDrawableHeightEnd;
                }
            }

Upvotes: 5

Andrew Aitken
Andrew Aitken

Reputation: 338

There is a similar method called setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int) where the parameters refer to start, top, end, bottom

You need to have min API level 17 or higher though.

Upvotes: 8

Related Questions