17

我的初始代码行位于被覆盖的方法内onGlobalLayout()

img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 100));

覆盖方法中发生的 ClassCastException onGlobalLayout()-

错误日志:

09-02 14:25:35.326: E/AndroidRuntime(5187): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.support.v4.view.ViewPager$LayoutParams
09-02 14:25:35.326: E/AndroidRuntime(5187):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1319)
09-02 14:25:35.326: E/AndroidRuntime(5187):     at android.view.View.measure(View.java:15181)
09-02 14:25:35.326: E/AndroidRuntime(5187):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
09-02 14:25:35.326: E/AndroidRuntime(5187):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
09-02 14:25:35.326: E/AndroidRuntime(5187):     at android.view.View.measure(View.java:15181)
09-02 14:25:35.326: E/AndroidRuntime(5187):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
09-02 14:25:35.326: E/AndroidRuntime(5187):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)

当我执行以下操作以解决其他 SO 帖子中指出的上述错误时:

img.setLayoutParams(new ViewPager.LayoutParams(ViewPager.LayoutParams.MATCH_PARENT, 100));

然后,我得到编译时错误:

The constructor ViewPager.LayoutParams(int, int) is undefined

xml 中的 ViewPager 定义如下:

<android.support.v4.view.ViewPager
 android:id="@+id/HView"
 android:layout_width="560dp"
 android:layout_height="255dp"
 android:layout_centerHorizontal="true"
 android:layout_marginLeft="160sp"
 android:layout_marginTop="110sp"
 android:layout_marginBottom="80sp">
 </android.support.v4.view.ViewPager>
4

3 回答 3

30

您的图像已经具有布局参数。您可以像这样修改现有的布局参数,而不是用新对象替换它们(在这种情况下是错误的类型,ViewPager期望它们是ViewPager.LayoutParams):

ViewGroup.LayoutParams params = img.getLayoutParams();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = 100;
img.requestLayout();

请注意,无条件地请求重新布局onGlobalLayout()可能是个坏主意,会导致无限的布局传递。我自己还没有验证是否是这种情况。

于 2013-09-02T09:15:19.713 回答
0

您应该确保LayoutParam您使用的类来自正确的父 Layout 类。并且您需要设置 LayoutParams 所在的ViewGroup位置,作为需要知道要分配给子 View 的大小ViewPager的父级。View例如,在您的情况下ViewGroupRelativeLayout您需要使用RelativeLayout.LayoutParams该类。

您可以尝试以下操作:

img.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 100));
于 2013-09-02T09:39:29.317 回答
0

这样做

img.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100));

更新

 LayoutParams params = img.getLayoutParams();
         params.width = LayoutParams.MATCH_PARENT;
         params.height = 100;
         img.setLayoutParams(params);
于 2013-09-02T09:05:46.490 回答