在父活动中访问Fragment viewPager

时间:2017-09-27 07:18:37

标签: android android-fragments android-viewpager

我的应用程序中存在问题,我在活动中加载了一个片段,在片段中我使用了ViewPager(用于TabLayout),所以我想处理ViewPager的BackPressed。 因为片段中没有OnKeyDown override method可用,所以我想在我的Parent Activty中使用Fragment ViewPager,因此我可以在onBackPressed() method Activity中处理这种情况。

活动代码:

fragment= new TabFragment();
if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.containerView, fragment);
        ft.commitAllowingStateLoss();
       // ft.commit();
    }
@Override
public void onBackPressed() {

if (isMainShown) {
   // want the refrence of view pager so i can handle ViewPager on backPress

    }
else {

   //display tab fragment
}
    //super.onBackPressed();
}

TabFragment:

public class TabFragment extends Fragment {


public TabFragment() {
    // Required empty public constructor
}
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ; View x;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    x=inflater.inflate(R.layout.content_main_menu,null);
    tabLayout=(TabLayout) x.findViewById(R.id.tabs);
    viewPager =(ViewPager) x.findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    //viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    viewPager.setOffscreenPageLimit(1);
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });
return x;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onDetach() {
    super.onDetach();

    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);

    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}



private void setupViewPager(ViewPager viewPager) {
    MyAdapter adapter = new MyAdapter(getChildFragmentManager());
    adapter.addFragment(new TabOne(), "TAb1");
    adapter.addFragment(new TabTwo(), "Tab2");

    viewPager.setAdapter(adapter);

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            final InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(x.getWindowToken(), 0);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}


private class MyAdapter extends FragmentPagerAdapter{
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }
    void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        return super.instantiateItem(container, position);
    }
}


}......

1 个答案:

答案 0 :(得分:2)

onBackPressed()

中添加此代码
fragobjTab = (TabFragment) getSupportFragmentManager().findFragmentById(R.id.containerView);
        try {
            fragobjTab.onBackPressed();

        }catch (Exception e){
            e.printStackTrace();
        }

在tabFragment中创建一个onBackPressed方法,并将setCurrentItem创建为ViewPager:

 public void onBackPressed()
{
    // set page to your viewPager
    // 0 is your first viewpager fragment
    viewPager.setCurrentItem(0,true);
}