Search code examples
androidandroid-viewpagerandroid-custom-view

Adding ViewPager to custom View on Android


I have a custom view looking like this

enter image description here

Is there a way to implement inner paging by ViewPager? I tried to create VP this way:

viewPager = (ViewPager) viewPagerLayout.findViewById(R.id.pager);

    viewPager = new ViewPager(getContext());
    viewPager.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    viewPager.setId(View.generateViewId());
    viewPager.setBackgroundColor(Color.BLUE);

In OnDraw method:

viewPager.measure(canvas.getWidth(), canvas.getHeight());
    viewPager.layout(0, 0, canvas.getWidth(), canvas.getHeight());
    if (viewPager != null)
        viewPager.draw(canvas);

Viewpager itself is drawn inside, like I want, but without paging ability. The method instantiateItem in adapter is never called. Standalone viewpager and adapter is working in another activity, but not inside custom view.


Solution

  • from your code I see you are "just drawing" ViewPager inside some method (onDraw?). it's like you are printing picture and want to talk with person on it... you have to add whole ViewPager to any container with Context to have ability to interact with it. thats why it is working straight inside Activity (which IS Context) or added by XML and not working when you just draw its "look"