gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:06:08 24 4
gpt4 key购买 nike

所以我有两个不同的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com