gpt4 book ai didi

java - 如何以编程方式设置 ViewPager layoutParams?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:03 27 4
gpt4 key购买 nike

我有下面的代码但是我得到了一个异常

java.lang.ClassCastException:android.support.v4.view.ViewPager$LayoutParams cannot be cast toandroid.view.ViewGroup$MarginLayoutParams

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question_details_full_photo_view_pager);
Bundle bundle = getIntent().getExtras();
ArrayList<String> imageUrls = bundle.getStringArrayList("imageUrls");
ImagePagerAdapter imagePagerAdapter = new ImagePagerAdapter(this, imageUrls, true);

android.support.v4.view.ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager_full_photo);


android.support.v4.view.ViewPager.LayoutParams layoutParams = new LayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
viewPager.setLayoutParams(layoutParams);


viewPager.setAdapter(imagePagerAdapter);
}

最佳答案

您真的不应该仅仅为了将宽度和高度设置为“match_parent”而以编程方式设置布局参数:这可以使用基本的 xml 声明轻松完成。

但是,如果您需要更高级的东西但您没有指定 - 例如调整边距或动态添加 View ,请考虑使用与您的情况匹配的布局包装 ViewPager。例如:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
android:id="@+id/view_pager_full_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>

在这种情况下,调整边距(例如):

ViewPager pager = (ViewPager) findViewById(R.id.view_pager_full_photo);
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) pager.getLayoutParams();
lp.topMargin += TOP_MARGIN_HEIGHT_PX;

等等

请注意,在这种情况下,调用 pager.getLayoutParams() 返回的布局参数是包装 RelativeLayout 的参数 - 它可以更容易地根据您的需要进行操作。

关于java - 如何以编程方式设置 ViewPager layoutParams?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17831672/

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