在寫自定義view時候獲取子view 的Margin數據時候使用
LayoutParams childLayoutParams = child.getLayoutParams();
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams;
報錯,顯示類初始化異常。
解決方法:
ViewGroup.LayoutParams params = child.getLayoutParams();
ViewGroup.MarginLayoutParams marginParams = null;
//獲取view的margin設置參數
if (params instanceof ViewGroup.MarginLayoutParams) {
marginParams = (ViewGroup.MarginLayoutParams) params;
} else {
//不存在時創建一個新的參數
//基於View本身原有的佈局參數對象
marginParams = new ViewGroup.MarginLayoutParams(params);
}
判斷是否存在,不存在就需要自己去創建