-4

Hello every body i made a weather application and i have 3 tabs i want to make tab 2 the default tab when i run the app

that's my code :

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
      switch (position)
      {
          case 0:
              Tab1 tab1=new Tab1();
              return tab1;
          case 1:
              Tab2 tab2=new Tab2();
              return tab2;
          case 2:
              Tab3 tab3=new Tab3();
              return tab3;
      }
        return null;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "NextDay";
            case 1:
                return "Today";
            case 2:
                return "3rd Day";
        }
        return null;
    }
}
Muthukrishnan Rajendran
  • 11,122
  • 3
  • 31
  • 41
Laith Abdo
  • 21
  • 3

2 Answers2

1

In your host Activity, at the end of onCreate call mViewPager.setCurrentItem(1);

humazed
  • 74,687
  • 32
  • 99
  • 138
0

You can go with this one. After setting the adapter in your host activity you should set the current item to 1.

public class MyActivity extends AppCompatActivity{

     SectionsPagerAdapter pagerAdapter;
     ViewPager myViewPager;
     public static final int PAGER_CURRENT_ITEM = 1;

     @Override
     protected void onCreate(Bundle savedInstanceState){
            setContentView(R.layout.activity_main);
            myViewPager = (ViewPager) findViewById(R.is.view_pager_id);
            pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
            viewPager.setAdapter(pagerAdapter)
            viewPager.setCurrentItem(PAGER_CURRENT_ITEM);
     }
}
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Aalap Patel
  • 2,058
  • 2
  • 17
  • 31
  • 1
    Your code is invalid. First you’re not calling `super()` 2nd your `onCreate` signature is wrong, 3rd, this doesn’t do what the OP asked for. 4th, you can’t findViewById in onCreate() if you haven’t set the content… etc. – Martin Marconcini Aug 18 '17 at 21:54
  • people are not supposed to just copy and paste whatever is written here this is just a prototype.. main concern should be just how the viewpager and adapter should set.. – Aalap Patel Aug 18 '17 at 22:11
  • Posters are supposed to spend enough time to format and provide accurate and useful information. Not only you’re not solving the OP’s problem, you’re also adding confusing information. There was no need to paste all this code if it wasn’t going to help. You could have just tell the OP to read View Pager’s documentation, more specifically, `setCurrentItem(Int)`. – Martin Marconcini Aug 19 '17 at 04:22