Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set ViewPager layoutParams programmatically?

I have the following code but I get an exception

java.lang.ClassCastException: android.support.v4.view.ViewPager$LayoutParams cannot be cast to 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);
}
like image 587
code511788465541441 Avatar asked Dec 25 '22 23:12

code511788465541441


1 Answers

You really shouldn't be setting the layout params programmatically just for setting up width and height to "match_parent": this could easily be done using fundamental xml declarations.

If however there's something more advanced you need that you didn't specify - such as adjusting margins or adding views dynamically, consider wrapping the ViewPager with a layout matching your case. For example:

<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 margins (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;

etc.

Note that in this case the layout params returned by the call to pager.getLayoutParams() are those of the wrapping RelativeLayout - which could be more easily manipulated to your fit your needs.

like image 168
d4vidi Avatar answered Dec 28 '22 13:12

d4vidi