gpt4 book ai didi

android - ClassCastException ViewGroup$LayoutParams 无法转换为 ViewPager$LayoutParams

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:20:44 25 4
gpt4 key购买 nike

我的初始代码行位于重写方法 onGlobalLayout() 中:

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

重写方法 onGlobalLayout() 中发生 ClassCastException-

错误日志:

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

ViewPager 在 xml 中的定义如下:

<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) :

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

请注意,在 onGlobalLayout() 中无条件请求重新布局可能不是一个好主意,会导致无限次布局遍历。是不是这样我自己也没有验证过。

关于android - ClassCastException ViewGroup$LayoutParams 无法转换为 ViewPager$LayoutParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18569267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com