全局设置APP为黑白模式的两种方案

  • 想必大家都被清明节国家哀悼日时各大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);
  }

已上两种方案就都可以实现APP黑白模式;方案2在复杂webView显示上可能会有些问题;

结束语:

       已上方案也是来源网友分享,这里只是汇总手敲验证了一下;在此感谢原创该方案的大神;

发布了3 篇原创文章 · 获赞 4 · 访问量 2216

猜你喜欢

转载自blog.csdn.net/SHANGJINYAO/article/details/105404121