以编程方式设置android textView drawableEnd

nul*_*ter 10 layout android

如何从java代码中设置android:drawableEndof TextView?在setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)可以在左,右,只有顶部和底部使用。如何设置drawableEnd

小智 12

要以编程方式设置 drawableend,请使用以下代码。为我工作。

   rowTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_call_black_24dp, 0);
Run Code Online (Sandbox Code Playgroud)


小智 8

有一个类似的方法叫做 setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int) 其中参数指的是开始,顶部,结束,底部

不过,您需要具有最低 API 级别 17或更高级别


小智 5

如果您使用 kotlin,我可以为 EditText 与 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)
Run Code Online (Sandbox Code Playgroud)

添加这些扩展后,您可以按如下方式使用 Drawables:

drawableEnd = context.getDrawable(R.drawable.ic_close_black)
Run Code Online (Sandbox Code Playgroud)

我认为这里有必要使用“setCompoundDrawablesRelativeWithIntrinsicBounds”方法。因为在实现内部,它设置了变量 mDrawableEnd 和 mDrawableStart 的值。这些变量在 left 和 rigt 中被替换,如果不是 null,这可以在 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;
                }
            }
Run Code Online (Sandbox Code Playgroud)