在代码中实现android:tint效果
Android着色效果tint
Android有个tint的着色效果,这样有些纯色图片,如果需要显示别的颜色效果,直接加上就行,特别方便。这个网上一搜就有,效果如图:
android:tint="@color/x" 我这个原本是个黑色的图标,加上这句,就可以显示各种颜色。 使用很简单,直接在XML加上android:tint="@color/colorPrimary"
就行;如果是背景,加上android:backgroundTint="@color/colorPrimary"
就行,比单纯设置方便多了。 比如Button如果设置android:background="@color/colorPrimary"
为纯颜色,那样会没有点击效果,需要点击效果还需要写个selector效果的drawable。如果要在Android5.0之上显示涟漪效果,还需要在drawable-v21中创建一个同名字的ripple效果的drawable XML写法简单,在代码中却有点麻烦。 网上搜索出来的方法有两种: 第一种不去区分版本,使用V4包的android.support.v4.graphics.drawable.DrawableCompat
ImageView image = new ImageView(context);Drawable up = ContextCompat.getDrawable(context,R.drawable.ic_sort_up);Drawable drawableUp= DrawableCompat.wrap(up);DrawableCompat.setTint(drawableUp, ContextCompat.getColor(context,R.color.theme));image.setImageDrawable(drawableUp);
第二种只能在API21以上使用
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ImageView image = new ImageView(context); image.setImageResource(R.drawable.ic_sort_down); image.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(context,R.color.theme)));}
第一种虽然好用,且向下兼容,但有个问题,就是如果我在A界面使用,先打开A界面,再去打开有使用同一个图片的B界面,会发现即使B界面的该ImageView没使用Tint,也会有对应的着色效果。除非先进入的B界面,或者退出应用。
看有个DrawableCompat.unwrap(...)
方法,试了一下,不管用,stackoverflow找到答案
http://stackoverflow.com/questions/30945490/drawablecompat-unwrap-is-not-working-pre-lollipop
试了一下,可以了,完整如下:
ImageView image = new ImageView(context);Drawable up = ContextCompat.getDrawable(context,R.drawable.ic_sort_up);Drawable drawableUp= DrawableCompat.wrap(up);DrawableCompat.setTint(drawableUp, ContextCompat.getColor(context,R.color.theme));image.setImageDrawable(drawableUp);layoutParams.addRule(RelativeLayout.RIGHT_OF, text.getId());addView(image, layoutParams);Drawable up1 = ContextCompat.getDrawable(context,R.drawable.ic_sort_up);Drawable drawableUp1= DrawableCompat.unwrap(up1);DrawableCompat.setTintList(drawableUp1, null);
倒数第三行写的那样,需要重新弄个Drawable 出来,用的同一个会导致之前设置的着色无效;倒数第二行测试使用wrap();也没出问题;最后一行一定用后面的那个Drawable ,用原来那个也会导致之前设置的着色无效。即使他们放在addView()
之后。
当然,最后三行完整放在image.setImageDrawable(drawable);
前面也是没有问题的,这边只是为了方便说明。
这些只是个人随便写的,又刚好有效,写法不一定对。
更多相关文章
- Android实现书籍翻页效果--扩展版
- Android 实现ListView 3D效果 - 2 - 弹性滚动,Fling
- 数据存储和界面笔记
- Android学习之 UI效果
- 界面编程之基本界面组件(5)ToggleButton(状态开关按钮)
- Android官方设计常用icon以及color颜色RGB值和对应颜色效果图
- 【Android开发学习27】界面控件之进度条(ProgressBar)
- 【Android 界面效果47】RecyclerView详解
- android抽屉效果