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

标签 android android-layout drawable android-drawable layerdrawable

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

所以我有一个 ImageButton这是 48x48 dp这就是最后的 Drawable去。第一个Drawable是一个加号按钮 (20x20 dp),第二个是加号按钮下方的小点 (4x4 dp)。

加号按钮 Drawable使用字体字形加载。我正在创建点按钮 Drawable使用此 xml fragment :

<?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>

我的第一种方法是同时添加 DrawablesLayerDrawable ,但是当我这样做时,xml 中指定的点的宽度/高度属性将被忽略,并且它会延伸以覆盖加号图标。

LayerDrawable finalDrawable = new LayerDrawable(new Drawable[] {plusIcon, dotIcon});

以上结果:



我尝试的第二种方法是使用 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);

上面的代码 fragment 最终将点放在了正确的位置,但它也开始影响加号按钮的位置和大小,最终看起来像这样:
enter image description here

但我真正想要的是在 ImageButton 的中心添加一个加号按钮和它正下方的加号图标。有谁知道我哪里出错了以及如何正确放置两个可绘制对象?

PS:我的应用程序支持 API 15+,所以我不能使用 LayerDrawable 中的一堆方法的 API 类似于 setLayerGravity , `setPaddingMode 等

最佳答案

编辑

此代码适用于 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);

原创

以下代码适用于我:

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);

这会产生以下用户界面:

enter image description here

关于android - 如何在 Android 中动态合并两个 Drawable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152768/

相关文章:

android - 如何在其父级的中心对齐 LinearLayout?

java - 如何为布局的宽度和高度设置动画?

android - 如何与 Google Play 服务交互以查询图片?

java - 在 NavigationView 中获取 NullPointerException

android - 使用 gradle 从 android 测试到 Sonar 的代码覆盖率

android - drawable-xxxhdpi 的正确图标大小是多少?

android - 如何在 XML drawable 中创建一个具有两个弯曲边的矩形?

android - 根据选择器中选择的应用程序,将不同的文本设置为 ACTION_SEND Intent

java - 获取结帐按钮以导航到结帐页面

可绘制着色与 ColorFilter