Home > front end >  How can I apply the same attributes to different viewpagers
How can I apply the same attributes to different viewpagers

Time:09-22

In my main activity, I currently have 3 viewpager2 with the same attributes. I implemented it by repeating the same block of codes but it looks too messy. Is there a better way to implement these attributes without the repetition? is it possible to use another class?

private void setupRecommendViewPager() {
        ViewPager2 recommendViewPager = findViewById(R.id.recommendViewPager);
        recommendViewPager.setClipToPadding(false);
        recommendViewPager.setClipChildren(false);
        recommendViewPager.setOffscreenPageLimit(3);
        recommendViewPager.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
        CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
        compositePageTransformer.addTransformer(new MarginPageTransformer(10));
        recommendViewPager.setPageTransformer(compositePageTransformer);

        ViewPager2 topDesViewPager = findViewById(R.id.topDesViewPager);
        topDesViewPager.setClipToPadding(false);
        topDesViewPager.setClipChildren(false);
        topDesViewPager.setOffscreenPageLimit(3);
        topDesViewPager.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
        //CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
        compositePageTransformer.addTransformer(new MarginPageTransformer(10));
        topDesViewPager.setPageTransformer(compositePageTransformer);

        ViewPager2 topAttractionViewPager = findViewById(R.id.topAttractionViewPager);
        topAttractionViewPager.setClipToPadding(false);
        topAttractionViewPager.setClipChildren(false);
        topAttractionViewPager.setOffscreenPageLimit(3);
        topAttractionViewPager.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
        //CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
        compositePageTransformer.addTransformer(new MarginPageTransformer(10));
        topAttractionViewPager.setPageTransformer(compositePageTransformer);
    }

CodePudding user response:

You can create a function with the argument of ViewPager like below:

private void setupViewPager(ViewPager2 viewPager) {
    viewPager.setClipToPadding(false);
    viewPager.setClipChildren(false);
    viewPager.setOffscreenPageLimit(3);
    viewPager.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
    //CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
    compositePageTransformer.addTransformer(new MarginPageTransformer(10));
    viewPager.setPageTransformer(compositePageTransformer);
}

Call your function like this:

setupViewPager(findViewById(R.id.recommendViewPager));
setupViewPager(findViewById(R.id.topDesViewPager));
setupViewPager(findViewById(R.id.topAttractionViewPager));
  • Related