繁体   English   中英

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

[英]How can I set ViewPager layoutParams programmatically?

我有以下代码,但出现异常

java.lang.ClassCastException: android.support.v4.view.ViewPager$LayoutParams 不能转换为 android.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 声明轻松完成。

但是,如果您需要未指定的更高级的东西 - 例如调整边距或动态添加视图,请考虑使用与您的情况匹配的布局包装 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布局参数- 可以更轻松地操作以满足您的需要。

这是因为您在此上下文中误解了LayoutParams :设置 ViewPager 的布局参数会将其布局在其父级(即 ViewGroup)中。 因此,您必须传递ViewGroup.LayoutParams的实例。
如果您想在 ViewPager 中布置组件,则必须使用ViewPager.LayoutParams实例设置子组件的布局参数

val pager = findViewById(R.id.view_pager);

val params = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT); params.setMargins(44, 44, 44, 44); pager.layoutParams = params

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM