简体   繁体   中英

android how to set particular item position for viewpager when onBackPressed()?

// Here is the adapter for viewpager

 public void setupViewPager(){
    pageAdapter = new PageAdapter(getSupportFragmentManager());
                pageAdapter.addFragment(FragmentDesigns.newInstance(), "INDIAFILINGS");
                icfo = ICFO.newInstance();
                pageAdapter.addFragment(icfo, "iCFO PLATFORM");
                viewPager.setAdapter(pageAdapter);
                tabLayout.setupWithViewPager(viewPager);
    // here code to set particular item in viewpager
    int pageRedirect;
                pageRedirect=CommonClass.getPageRedirect();
                try {
                    if(pageRedirect!=0){
                        viewPager.setCurrentItem(1);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
    }

I am implementing viewpager with two fragments.In second Fragment i have list of data if user selects any item from a list it will redirect to another activity.If user does onbackPress in activity i want to set viewpager second fragment as a current fragment

Note:The issue is when i do onbackPress the application is getting close

override the onBackPressed method in your second activity so that system default behaviour does not happen

@Override
public void onBackPressed() {

   Intent firstintent = new Intent(context,Firstactivity.class);

firstintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);

   startActivity(firstintent);

}

This will open the first activity, close the second activity and deliver the result in the onNewIntent of the first activity

In your first activity override onNewIntent so that the back press result is found

@Override
protected void onNewIntent(Intent intent) {
    yourvp.setCurrentItem(positionyouneed);
}

This should do the trick for you

@Override
    public void onBackPressed() {
        if (viewPager.getCurrentItem() != 0) {
            viewPager.setCurrentItem(secondViewpagerItemPostion,false);
        }else{
             super.onBackPressed();
        }

    }

将您的当前视图分页器位置存储在sharepref中,如果不为null,则检查它的位置,然后viewpager.setCurrentItem(shareprefPosition);

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