Tag Archives: onclick

Tutorial: Using a Button To Switch Pages in a ViewPager [Android Studio]

OK, so Android Studio (like its ancient forefather Eclipse) supports the ViewPager navigation type, which allows you to set up multi-page navigation without any work. However, I’ve noticed that many people don’t quite seem to get the hang of swiping and give up on trying to switch pages. It’s best to provide an alternate form of navigation for them – in the form of the ubiquitous button, linked to a function that switches the active page. As an example, I’m going to make a function that makes the ViewPager jump to the second page.

  1. In the little fragment_main_dummy.xml file hidden away in src/main/java/res/layout (or whatever the name of the file – in which you want the button to be – is), add a new Button component (using the Design view if you like that). Switch to Code view and locate the Button component.before
  2. At the end of the Button component, before the ending /> press Enter and add this line of code:


  3. Save the file. Now, the last part of this can be done in two ways:
    1. First method: Put your cursor somewhere on the android:onClick line and press Alt-Enter (Option-Enter on Macs). Select “Create onClick event handler”.
      Select MainActivity when asked which activity you want to create the onClick handler in.choose_activity
      It makes a nice function called jumpToPage in your main Activity class.
      Place your cursor just after the opening brace and press enter. Add this line to the function body:
    2. mViewPager.setCurrentItem(1);

      Save the file.

    3. Second method: Switch to your MainActivity.java file. At the end of the onCreateOptionsMenu function, type this in (or copy-paste if you’re lazy):
      public void jumpToPage(View view) {

      Save the file.

  4. This is what you should have in MainActivity.java now:

You’re done!

[In response to a friend’s request, who asked for the pictures :D]