天天看點

Android動态設定VIew寬高

一般動态設定VIew寬高的寫法是:

View child = new View(this);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) child.getLayoutParams();
        layoutParams.width = 120;
        layoutParams.height = 120;
        child.setLayoutParams(layoutParams);
           

這裡需要注意的是:LayoutParams所導的包應該是這個VIew的父布局所對于的類型,也就是說如果包裹這個View的是LinearLayout,那就應該導LinearLayout,是RelativeLayout就應該導入RelativeLayout,否則運作會出錯,類型轉換異常java.lang.ClassCastException: