Lint警告:Avoid object allocations during draw/layout operations (preallocate and reuse instead)
不要在自定義View的onMeasure、onLayout、onDraw等方法裏面做new對象的操作。
因爲實例化對象是會耗性能的,而這幾個方法會被多次調用,所以需要將對象作爲屬性,在初始化的時候就實例化好對象,在這些方法裏面直接用就行了!
1.若一些參數必須在onMeasure/onLayout/onDraw中獲取,則可以先在構造函數中創建對象,在onMeasure/onLayout/onDraw中賦值:
private void init(){ //在構造函數中進行初始化
// 獲取屏幕大小:通過Resources獲取
DisplayMetrics dm2 = getResources().getDisplayMetrics();
mBitmap = Bitmap.createBitmap(dm2.widthPixels, dm2.heightPixels, Bitmap.Config.RGB_565);//ARGB_8888
}
public void onLayout(){//在onLayout方法中賦值:
screenW = fX = getWidth();
screenH = fY = getHeight();
mBitmap.setHeight((int) screenH);
mBitmap.setWidth((int) screenW);
}
ps:
2). getWindowManager()是Activity的方法
2.把只能調用一次的代碼使用個布爾內置變量進行判斷,讓其只調用一次。