0

这段代码要了我的命。我正在尝试以LinearLayout编程方式设置(包含子项)的宽度和高度,并且应用程序正在中断。这是代码:

LinearLayout ll = (LinearLayout) findViewById(R.id.right_t);
ll.setLayoutParams(new android.widget.LinearLayout.LayoutParams(200, 200));

如您所见,我 100% 确定我可以使用正确的布局参数。然而,该应用程序因错误而中断

1-22 19:54:13.135: ERROR/AndroidRuntime(4560): FATAL EXCEPTION: main
    java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
    at android.widget.RelativeLayout$DependencyGraph.findRoots(RelativeLayout.java:1317)
    at android.widget.RelativeLayout$DependencyGraph.getSortedViews(RelativeLayout.java:1264)
    at android.widget.RelativeLayout.sortChildren(RelativeLayout.java:292)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:314)
    at android.view.View.measure(View.java:12863)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
    at android.view.View.measure(View.java:12863)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
    at android.view.View.measure(View.java:12863)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2256)
    at android.view.View.measure(View.java:12863)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1197)
    at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2585)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4507)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
    at dalvik.system.NativeStart.main(Native Method)

LinearLayout与孩子一起设置在它自己的 XML 文件中,并通过<include>标记加载到主 XML 中。

有任何想法吗?为什么当我不这样做时它会说我正在LinearLayout尝试?RelativeLayout

4

1 回答 1

5

LayoutParams 的类型对应于要在其中添加LinearLayout. 所以我猜在这种情况下父布局是 aRelativeLayout并且你应该创建 aRelativeLayout.LayoutParams而不是LinearLayout.LayoutParams.

于 2012-11-22T19:02:33.947 回答