以编程方式设置android textView drawableEnd

时间:2013-10-15 14:14:08

标签: android layout

如何从java代码中设置android:drawableEnd的{​​{1}}? TextView只能在左侧,右侧,顶部和底部使用。如何设置setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)

3 个答案:

答案 0 :(得分:4)

有一个类似的方法叫做setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int),其中参数引用start,top,end,bottom

您需要 min API level 17 或更高。

答案 1 :(得分:3)

如果你使用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)

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

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

我认为这里有必要使用'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;
                }
            }

答案 2 :(得分:1)

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

   notify_register_dispatch("com.apple.iokit.hid.displayStatus", &notify_token, dispatch_get_main_queue(), ^(int token) {
    uint64_t state = UINT64_MAX;
    notify_get_state(token, &state);
    //notify_cancel(token);
    debug("com.apple.iokit.hid.displayStatus = %llu", state);
});