如何在代码中设置LinearLayout的高度
main.xml声明
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/context"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/linear_layout"
android:orientation="vertical">
<TextView
android:id="@+id/hello_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button"
android:text="Click me Hide System statusbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:track="@drawable/switch_track_light"
android:thumb="@drawable/switch_inner_light"
android:textOn="@string/empty"
android:textOff="@string/empty1"/>
</LinearLayout>
</FrameLayout>
java文件onCreate中设置LinearLayout的width和height
mLinearLayout = (LinearLayout) findViewById(R.id.linear_layout);
//方法1:
mLinearLayout.setLayoutParams(
new LinearLayout.LayoutParams(400, 200));
方法1会报下面的异常
01-03 01:48:12.914: E/AndroidRuntime(3353): FATAL EXCEPTION: main
01-03 01:48:12.914: E/AndroidRuntime(3353): java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams
//方法2: 可以正确使用
ViewGroup.LayoutParams lp;
lp= mLinearLayout.getLayoutParams();
lp.width=400;
lp.height=200;
mLinearLayout.setLayoutParams(lp);