1. 使用app前缀(app:backgroundTint,app:backgroundTintMode),如果使用android前缀,在低版本上是拿不到值的,因为这些属性是5.0以后才加入的。

2. 自定义ATTRS数组,使用obtainStyledAttributes方法得到app:backgroundTint和app:backgroundTintMode的值。

3. 使用v4包中的ViewCompat类----ViewCompat.setBackgroundTintList,ViewCompat.setBackgroundTintMode方法设置tint。

大功告成,这样可以同时兼容4.x和5.x。如果只在java代码中使用,其实只要使用ViewCompat类就好了,其实底层原理是一样的,都是ColorFilter、PorterDuff在起作用,ViewCompact针对不同版本进行了封装,更容易使用了,不用我们去管底层实现细节。

我自己写了个工具类,代码如下

package com.sky.support;

import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View; /**
* Created by sky on 2015/9/15.
* <p/>
* View Utils
*/
public class ViewUtils { private static final int[] TINT_ATTRS = {
R.attr.backgroundTint, //in v7
R.attr.backgroundTintMode, //in v7
}; public static void supportTint(View view, AttributeSet attrs) {
TypedArray a = view.getContext().obtainStyledAttributes(attrs, TINT_ATTRS);
if (a.hasValue(0)){
//set backgroundTint
ColorStateList colorStateList = a.getColorStateList(0);
ViewCompat.setBackgroundTintList(view, colorStateList);
}
if (a.hasValue(1)){
//set backgroundTintMode
int mode = a.getInt(1, -1);
ViewCompat.setBackgroundTintMode(view, parseTintMode(mode, null));
}
a.recycle();
} /**
* Parses a {@link android.graphics.PorterDuff.Mode} from a tintMode
* attribute's enum value.
*
* @hide
*/
public static PorterDuff.Mode parseTintMode(int value, PorterDuff.Mode defaultMode) {
switch (value) {
case 3:
return PorterDuff.Mode.SRC_OVER;
case 5:
return PorterDuff.Mode.SRC_IN;
case 9:
return PorterDuff.Mode.SRC_ATOP;
case 14:
return PorterDuff.Mode.MULTIPLY;
case 15:
return PorterDuff.Mode.SCREEN;
case 16:
return PorterDuff.Mode.ADD;
default:
return defaultMode;
}
}
}

最新文章

  1. 表单 - Form - 无刷新提交原理
  2. WPF DataGrid &ndash; Dynamically updating DataGridComboBoxColumn
  3. G面经prepare: Set Intersection &amp;&amp; Set Difference
  4. Android2.2快速入门 zz
  5. mfc unicode下一些容易容易搞混的基本类型
  6. 【Reporting Services 报表开发】— 页码编列
  7. input 文本框和 img 验证码对齐问题
  8. Java Spring boot 系列目录
  9. JAVA 实现通过URL下载文件到本地库
  10. 【HDU 5233】Tree chain problem (树形DP+树剖+线段树|树状数组)最大权不相交树链集
  11. 我的第一篇Markdown博客
  12. 【2014】【辛星】【php】【秋季】【2】第一个php程序
  13. html5本地数据库(一)
  14. PCB板蛇形走线有什么作用
  15. Xamarin C# Android for Visual Studio 平台安装
  16. 通过spring实现javamail发送邮件功能
  17. swift 之归档和解归档
  18. 关于Application_End 与 Application_Start事件触发情况的测试(待续)
  19. getMemory的经典例子
  20. Magento2 API 服务合同设计模式 依赖注入 介绍

热门文章

  1. hive2.1.0安装
  2. Arch Linux 安装博通 BCM4360 驱动(Arch Linux, Ubuntu, Debian, Fedora...)
  3. 百度地图-省市县联动加载地图 分类: Demo JavaScript 2015-04-26 13:08 530人阅读 评论(0) 收藏
  4. jquery实现页面交互的几个小例子
  5. MSSQ调优所需用的语句
  6. Windows远程连接CentOS桌面
  7. erlang mac os 10.9 卸载脚本
  8. CSS will-change 属性
  9. 用PS去除图片中文字的6个方法
  10. C语言2