清明节国家哀悼日时各大APP的黑白模式切换,以下介绍两种方案快速设置APP为黑白模式
方案1: 在Activity 中增加如下代码(可以放到项目的BaseActivity中):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxx);
//主要是如下代码:
View decorView = getWindow().getDecorView();
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
paint.setColorFilter(new ColorMatrixColorFilter(cm));
decorView.setLayerType(View.LAYER_TYPE_HARDWARE,paint);
}
方案2:
1、先定义一个GrayFrameLayout布局
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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、在Activity(可以放到项目的BaseActivity中)
@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);
}
|