ClassCastException ViewGroup $ LayoutParams无法转换为ViewPager $ LayoutParams [英] ClassCastException ViewGroup$LayoutParams cannot be cast to ViewPager$LayoutParams
问题描述
我的初始代码行在覆盖的方法 onGlobalLayout()
内:
My initial code line is inside the overridden method onGlobalLayout()
:
img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 100));
ClassCastException发生在重写的方法 onGlobalLayout()
-
ClassCastException occuring in the overridden method 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帖子所示:
And when I do the following in order to resolve the above error as indicated in other SO posts:
img.setLayoutParams(new ViewPager.LayoutParams(ViewPager.LayoutParams.MATCH_PARENT, 100));
然后,我得到编译时间错误:
Then, I get the compile time error:
The constructor ViewPager.LayoutParams(int, int) is undefined
xml中的
ViewPager定义如下:
ViewPager in xml is defined like:
<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>
推荐答案
您的图像已经具有布局参数。 ViewPager
希望将它们替换为 ViewPager.LayoutParams $ c $,而不是用新对象替换(在这种情况下,这是错误的类型) c>),您可以像这样修改现有的布局参数:
Your image already has layout params. Instead of replacing them with a new object (which is of wrong type in this case, ViewPager
expects them to be ViewPager.LayoutParams
), you can modify existing layout params like this:
ViewGroup.LayoutParams params = img.getLayoutParams();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = 100;
img.requestLayout();
请注意,无条件地在 onGlobalLayout()$ c中请求重新布局$ c>可能是一个坏主意,导致布局遍历无限。我还没有亲自验证是否是这种情况。
Note that unconditionally requesting re-layout in onGlobalLayout()
can be a bad idea, leading to infinite layout passes. I haven't verified it myself whether this is the case.
这篇关于ClassCastException ViewGroup $ LayoutParams无法转换为ViewPager $ LayoutParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!