如何在Android中动态合并两个Drawable?

aks*_*t23 9 android drawable android-layout android-drawable layerdrawable

所以我有两个不同的Drawables需要合并并Drawable在运行时获得一个.我希望第一个Drawable位于顶部,另一个位于底部.我遇到了LayerDrawable它,看起来它正是我所需要的,但我在努力安排它时遇到了麻烦Drawables.

所以我有一个ImageButton48x48 dp,这是最终Drawable的结果.第一个Drawable是加号按钮(20x20 dp),第二个是dp加号按钮下方的小点(4x4 ).

加号按钮Drawable使用字体字形加载.我正在Drawable使用这个xml片段创建点按钮:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
       android:shape="oval">
    <solid
        android:color="@color/white_40"/>
    <size
        android:width="4dp"
        android:height="4dp"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

我的第一种方法是只既能补充DrawablesLayerDrawable,但是当我这样做,宽度/高度在XML中指定的点被忽略的属性,并将其延伸到覆盖的加号图标.

LayerDrawable finalDrawable = new LayerDrawable(new Drawable[] {plusIcon, dotIcon});
Run Code Online (Sandbox Code Playgroud)

以上结果如下:



我尝试的第二种方法是setLayerInset尝试定位两者Drawables.

    LayerDrawable finalDrawable = new LayerDrawable(new Drawable[] {plusIcon, dotIcon});
    finalDrawable.setLayerInset(0, 0, 0, 0, 0);
    finalDrawable.setLayerInset(1, dp(22), dp(44), dp(22), 0);
Run Code Online (Sandbox Code Playgroud)

上面的代码片段最终将点放在正确的位置,但它也开始影响加号按钮的位置和大小,最终看起来像这样:
在此输入图像描述

但我真正想要的是在它的中心加上加号按钮ImageButton.有没有人知道我哪里出错了?如何才能正确定位两个抽屉?

PS:我的应用支持API 15+,所以我不能使用LayerDrawableAPI中的一堆方法,比如setLayerGravity`setPaddingMode等.

Ben*_* P. 8

编辑

此代码适用于低于23的API级别:

ImageButton button = (ImageButton) findViewById(R.id.button);

Drawable plusIcon = ContextCompat.getDrawable(this, R.drawable.plus);
Drawable dotIcon = ContextCompat.getDrawable(this, R.drawable.oval);

int horizontalInset = (plusIcon.getIntrinsicWidth() - dotIcon.getIntrinsicWidth()) / 2;

LayerDrawable finalDrawable = new LayerDrawable(new Drawable[] {plusIcon, dotIcon});
finalDrawable.setLayerInset(0, 0, 0, 0, dotIcon.getIntrinsicHeight());
finalDrawable.setLayerInset(1, horizontalInset, plusIcon.getIntrinsicHeight(), horizontalInset, 0);

button.setImageDrawable(finalDrawable);
Run Code Online (Sandbox Code Playgroud)

原版的

以下代码适用于我:

ImageButton button = (ImageButton) findViewById(R.id.button);

Drawable plusIcon = ContextCompat.getDrawable(this, R.drawable.plus);
Drawable dotIcon = ContextCompat.getDrawable(this, R.drawable.oval);

LayerDrawable finalDrawable = new LayerDrawable(new Drawable[] {plusIcon, dotIcon});
finalDrawable.setLayerInsetBottom(0, dotIcon.getIntrinsicHeight());
finalDrawable.setLayerGravity(1, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);

button.setImageDrawable(finalDrawable);
Run Code Online (Sandbox Code Playgroud)

这产生以下ui:

在此输入图像描述

  • 我认为在这一点上,我们已经超出了LayerDrawable真正意图的范围.我考虑创建一个包含点和加号的矢量drawable,或者使用FrameLayout/ConstraintLayout(在按钮顶部)来定位两个drawable. (2认同)