大佬教程收集整理的这篇文章主要介绍了如何在Android中动态合并两个Drawable?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有一个48×48 dp的ImageButton,这是最终的Drawable所在的地方.第一个Drawable是加号按钮(20×20 dp),第二个是加号按钮下方的小点(4×4 dp).
加号按钮Drawable使用字体字形加载.我正在使用这个xml片段创建点按钮Drawable:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://scheR_683_11845@as.android.com/apk/res/android" android:shape="oval"> <solid android:color="@color/white_40"/> <size android:width="4dp" android:height="4dp"/> </shape>
我的第一种方法是将两个Drawables添加到LayerDrawable中,但是当我这样做时,忽略xml中指定的点的width / height属性,并且它会延伸以覆盖加号图标.
LayerDrawable finalDrawable = new LayerDrawable(new Drawable[] {plusIcon,dotIcon});
我尝试的第二种方法是使用setLayerInset来尝试定位两个Drawable.
LayerDrawable finalDrawable = new LayerDrawable(new Drawable[] {plusIcon,dotIcon}); finalDrawable.setLayerInset(0,0); finalDrawable.setLayerInset(1,dp(22),dp(44),0);
上面的代码片段最终将点放在正确的位置,但它也开始影响加号按钮的位置和大小,最终看起来像这样:
但我真正想要的是在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,dotIcon.geTintrinsicHeight()); finalDrawable.setLayerInset(1,horizontalInset,plusIcon.geTintrinsicHeight(),0); button.setImageDrawable(finalDrawablE);
原版的
以下代码适用于我:
ImageButton button = (ImageButton) findViewById(R.id.button); Drawable plusIcon = 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);
这产生以下ui:
以上是大佬教程为你收集整理的如何在Android中动态合并两个Drawable?全部内容,希望文章能够帮你解决如何在Android中动态合并两个Drawable?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。