android中如何在低版本(5.0之前)上使用tint(着色)属性
2024-10-18 06:20:18
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;
}
}
}
最新文章
- 表单 - Form - 无刷新提交原理
- WPF DataGrid &ndash; Dynamically updating DataGridComboBoxColumn
- G面经prepare: Set Intersection &;&; Set Difference
- Android2.2快速入门 zz
- mfc unicode下一些容易容易搞混的基本类型
- 【Reporting Services 报表开发】— 页码编列
- input 文本框和 img 验证码对齐问题
- Java Spring boot 系列目录
- JAVA 实现通过URL下载文件到本地库
- 【HDU 5233】Tree chain problem (树形DP+树剖+线段树|树状数组)最大权不相交树链集
- 我的第一篇Markdown博客
- 【2014】【辛星】【php】【秋季】【2】第一个php程序
- html5本地数据库(一)
- PCB板蛇形走线有什么作用
- Xamarin C# Android for Visual Studio 平台安装
- 通过spring实现javamail发送邮件功能
- swift 之归档和解归档
- 关于Application_End 与 Application_Start事件触发情况的测试(待续)
- getMemory的经典例子
- Magento2 API 服务合同设计模式 依赖注入 介绍
热门文章
- hive2.1.0安装
- Arch Linux 安装博通 BCM4360 驱动(Arch Linux, Ubuntu, Debian, Fedora...)
- 百度地图-省市县联动加载地图 分类: Demo JavaScript 2015-04-26 13:08 530人阅读 评论(0) 收藏
- jquery实现页面交互的几个小例子
- MSSQ调优所需用的语句
- Windows远程连接CentOS桌面
- erlang mac os 10.9 卸载脚本
- CSS will-change 属性
- 用PS去除图片中文字的6个方法
- C语言2