<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ll" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <RelativeLayout android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent">
以上是布局文件代碼,我想在代碼中重新設置rl的寬度
RelativeLayout relativeLayout = (RelativeLayout)this.findViewById(R.id.rl); RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(100, LayoutParams.MATCH_PARENT); relativeLayout.setLayoutParams(param);
就會報這個錯 Caused by: java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams 。
解決方法:relativeLayout 是LinearLayout的子控件,它的LayoutParams 應該是LinearLayout給他的。所以應該是LinearLayout.LayoutParam 。如果relativeLayout 有子控件的話,那它的子控件用的的就是relativeLayout 給他們的,才是RelativeLayout.LayoutParam。