简体   繁体   中英

Android ViewPager Layouts

I have one activity_main_layout with 3 linear layouts inside (layout1, layout2 and layout3). From my MainActivity I want to display specific layouts on buttonClicks. Like if firstButton is clicked then layout1 is displayed, secondButton displays layout2 and thirdButton displays layout3. I am using viewPager to achieve this. Here is my Code Below:

private class ViewPagerAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((View) object);
    }

    public Object instantiateItem(View collection, int position) {

        int resId = -1;
        switch (position) {
            case 0:
                resId = R.id.layout1;
                Log.e(TAG, "layout1 called");
                break;
            case 1:
                resId = R.id.layout2;
                Log.e(TAG, "layout2 called");
                break;
            case 2:
                resId = R.id.layout3;
                Log.e(TAG, "layout3 called");
                break;
        }
        return findViewById(resId);
    }

    @Override
    public void destroyItem(View collection, int position, Object view) {
        ((ViewPager) collection).removeView((View) view);
    }
}

layout1 being the default, it displays on the screen on starting the MainActivity.

When I see the log it displays

03-11 14:34:22.776  23506-23506/com.myapp.app E/MainActivity﹕ layout1 called
03-11 14:34:22.777  23506-23506/com.myapp.app E/MainActivity﹕ layout2 called

And then when i click secondButton Log shows layout3 called

Any idea on this? I am trying to achieve as shown in this image

ViewPager will call first 2 pages at initial load, and on page change it will load next page in memory.

In your case layout1 and layout2 will be called at initial level and when you move to layout2 it will load layout3 .

you can use setOffScreenPageLimit() to increase this number but bydefault it will load 2 pages at a time.

You can refer this regarding your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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