How can I customize the ViewPager layoutParams programmatically?

I have the following code, but I get an exception

java.lang.ClassCastException: android.support.v4.view.ViewPager $ LayoutParams cannot be dropped 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); } 
+4
source share
2 answers

You really don't have to set the layout parameters programmatically just to set the width and height to match_parent: this can easily be done using fundamental xml declarations.

If you need something more advanced that you didn’t specify — for example, adjusting fields or adding views dynamically, consider packing the ViewPager with a layout appropriate for your case. For instance:

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

In this case, to adjust the fields (for example):

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

and etc.

Note that in this case, the layout options returned by pager.getLayoutParams () are RelativeLayout shell options that can be more easily manipulated to suit your needs.

+5
source

This is because you misunderstood LayoutParams in this context: setting the layout options of your ViewPager will display it in its parent, which is a ViewGroup. Therefore, you must pass an instance of ViewGroup.LayoutParams .
If you want to place the component in your ViewPager view, you need to set the layout options for the child with an instance of ViewPager.LayoutParams

+3
source

Source: https://habr.com/ru/post/1493164/


All Articles