Android实现设置APP灰白模式效果
到特殊节日,伟人纪念日 ,等类似的时候 很多App都设置了符合主题的灰白模式,比如京东,如图所示:
![在这里插入图片描述]三种方案全局设置灰白模式:
方案一:
给Activity的顶层View设置置灰,实现全局置灰效果,下面我们来看看具体的实现过程。
可以在BaseActivity的onCreate方法中,使用ColorMatrix设置灰度
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//方案一
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);//灰度效果
paint.setColorFilter(new ColorMatrixColorFilter(cm));
getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE,paint);
}
这样就可以实现啦,这种方式还是比较简单的。
方案二:
该方法使用自定义layout,在dispatchdraw方法的时候,添加一层黑白色的bitmap,让界面开起来成为黑白模式。但是缺点明显,应用比较卡顿。
1、首先需要先定义一个GrayFrameLayout布局
public class GrayFrameLayout extends FrameLayout {
private Paint mPaint = new Paint();
public GrayFrameLayout(@NonNull Context context) {
super(context);
}
public GrayFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
mPaint.setColorFilter(new ColorMatrixColorFilter(cm));
}
@Override
protected void onDraw(Canvas canvas) {
canvas.saveLayer(null, mPaint, Canvas.ALL_SAVE_FLAG);
super.onDraw(canvas);
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.saveLayer(null, mPaint, Canvas.ALL_SAVE_FLAG);
super.dispatchDraw(canvas);
}
}
2、在BaseActivity的onCreateView方法中做如下处理
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
//方案二
if("FrameLayout".equals(name)){
int attributeCount = attrs.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
String attributeName = attrs.getAttributeName(i);
String attributeValue = attrs.getAttributeValue(i);
if(attributeName.equals("id")){
int id = Integer.parseInt(attributeValue.substring(1));
String resourceName = getResources().getResourceName(id);
if("android:id/content".equals(resourceName)){
GrayFrameLayout frameLayout = new GrayFrameLayout(this,attrs);
return frameLayout;
}
}
}
}
return super.onCreateView(parent, name, context, attrs);
}
方案三
有些特殊控件需要置灰,比如webview、H5页面、视频等
1、创建一个置灰的管理类
public class GrayManager {
private static GrayManager mInstance;
private Paint mGrayPaint;
private ColorMatrix mGrayMatrix;
public static GrayManager getInstance() {
if (mInstance == null) {
synchronized (GrayManager.class) {
if (mInstance == null) {
mInstance = new GrayManager();
}
}
}
return mInstance;
}
//初始化
public void init() {
mGrayMatrix = new ColorMatrix();
mGrayPaint = new Paint();
mGrayMatrix.setSaturation(0);
mGrayPaint.setColorFilter(new ColorMatrixColorFilter(mGrayMatrix));
}
//硬件加速置灰方法
public void setLayerGrayType(View view) {
if (mGrayMatrix == null || mGrayPaint == null) {
init();
}
view.setLayerType(View.LAYER_TYPE_HARDWARE, mGrayPaint);
}
}
2、特殊控件需要置灰的话直接调用setLayerGrayType()方法将view传进去,比如demo中让某个Activity置灰,那就在Activity里面调用:
GrayManager.getInstance().setLayerGrayType(getWindow().getDecorView());
三种方案都可以实现灰白模式,经过demo测试验证,可能由于测试范围比较狭隘可能还有其它情况,那就后面遇到再补充吧