10

如何从java代码android:drawableEnd中设置?只能用于左侧、右侧、顶部和底部TextViewsetCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)如何设置drawableEnd

4

3 回答 3

14

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

   rowTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_call_black_24dp, 0);
于 2019-02-08T10:38:51.477 回答
8

有一个类似的方法叫做 setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int) 参数指的是 start, top, end, bottom

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

于 2013-10-23T17:30:19.737 回答
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)

添加这些扩展后,您可以使用 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;
                }
            }
于 2018-06-08T16:06:45.957 回答