aks*_*t23 9 android drawable android-layout android-drawable layerdrawable
所以我有两个不同的Drawables
需要合并并Drawable
在运行时获得一个.我希望第一个Drawable
位于顶部,另一个位于底部.我遇到了LayerDrawable
它,看起来它正是我所需要的,但我在努力安排它时遇到了麻烦Drawables
.
所以我有一个ImageButton
48x48 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)
我的第一种方法是只既能补充Drawables
到LayerDrawable
,但是当我这样做,宽度/高度在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+,所以我不能使用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);
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: