問題: 自定義view MarginLayoutParams報錯

在寫自定義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);
                }

判斷是否存在,不存在就需要自己去創建

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章