在导航抽屉片段中保存viewpager片段的状态

时间:2018-02-22 05:35:22

标签: android navigation fragment drawer

我有导航抽屉。在导航抽屉的第一个碎片中有viewpager并且有来自network.Viewpager的信息也有2个片段。当我将片段切换到导航抽屉的设置片段并回到此片段时,一切都是我没有任何信息。我​​怎样才能保存这个片段的状态?或者我可以用哪种方法发送请求从网络中获取信息

MainActivity

          public class MainActivity extends AppCompatActivity implements 

        NavigationView.OnNavigationItemSelectedListener {

        private DrawerLayout drawer;

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);


    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.motherFragments, FragmentMainPage.newInstance("MainPage"))
            .commit();
}

@Override
public void onBackPressed() {
   drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home: {
            drawer.openDrawer(GravityCompat.START);
            break;
        }

    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    Fragment fragment = null;

    if (item.isChecked()) {
        drawer.closeDrawer(GravityCompat.START);
        return false;
    }
    switch (item.getItemId()) {

        case R.id.home: {
            fragment = new FragmentMainPage().newInstance("Sample");
            break;
        }
        case R.id.settings:{
            Intent intent = new Intent(this,SettingsActivity.class);
            startActivity(intent);
            break;
        }
        case R.id.incoming:{
            fragment  = new FragmentIncomingPage().newInstance("Sample");
            break;
        }

    }

    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction().replace(R.id.motherFragments, fragment)
                .commit();
        item.setChecked(true);

    }

    drawer.closeDrawer(GravityCompat.START);
    return true;
} }

导航抽屉的片段1

            public class FragmentMainPage extends Fragment implements 
         ViewPager.OnPageChangeListener {
             private Toolbar toolbar;
              private MainActivity activity;
           private TabLayout tabLayout;
             private ViewPager viewPager;

String[] names = {
        "Sample 1",
        "Sample 2"

};



private static FragmentMainPage myInstance;
public static FragmentMainPage newInstance(String testString){
    Bundle bundle = new Bundle();
    bundle.putString("test",testString);
    if(myInstance == null){
        myInstance = new FragmentMainPage();
    }
    myInstance.setArguments(bundle);
    return myInstance;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    activity = ((MainActivity) context);
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_fragment_main,container,false);
    toolbar = (Toolbar) view.findViewById(R.id.toolbar);

    activity.setSupportActionBar(toolbar);
    activity.setTitle(getResources().getText(R.string.bosh_sahifa));
    activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
    activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    setupViewpager(viewPager);
    tabLayout = (TabLayout) view.findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    viewPager.addOnPageChangeListener(this);
    setupTabName();

    return view;
}


private void setupViewpager(ViewPager viewPager) {
    MyAdapter adapter = new MyAdapter(getActivity().getSupportFragmentManager());
    adapter.addFragement(new Fragment_home1());
    adapter.addFragement(new Fragment_home2());

    viewPager.setAdapter(adapter);

}

private void setupTabName() {
    tabLayout.getTabAt(0).setText(names[0]);
    tabLayout.getTabAt(1).setText(names[1]);

}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);


}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {

}

@Override
public void onPageScrollStateChanged(int state) {

}

private class MyAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = 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();
    }
    public void addFragement(Fragment fragment){
        mFragmentList.add(fragment);
    }
}

}

导航抽屉的片段2

             public class FragmentIncomingPage extends Fragment  {
             private Toolbar toolbar;
               private MainActivity activity;




private static FragmentIncomingPage myInstance;
public static FragmentIncomingPage newInstance(String testString){
    Bundle bundle = new Bundle();
    bundle.putString("test",testString);
    if(myInstance == null){
        myInstance = new FragmentIncomingPage();
    }
    myInstance.setArguments(bundle);
    return myInstance;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    activity = ((MainActivity) context);
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_fragment_incoming,container,false);
    toolbar = (Toolbar) view.findViewById(R.id.toolbar);

    activity.setSupportActionBar(toolbar);
    activity.setTitle(getResources().getText(R.string.Incoming));
    activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
    activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    return view;
}

}

3 个答案:

答案 0 :(得分:0)

您可以使用 fragment.addToBackStack(null)方法。 等,

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, A);
ft.addToBackStack(null);
ft.commit();

答案 1 :(得分:0)

实现目标的方法很少。

  1. 您可以使用SharedPreferences通过mViewPager.getCurrentItem()保存当前片段,并在按导航抽屉按钮进入ViewPager活动后再次设置它。

  2. 使用BaseFragment并从Base Fragment实现您的片段,将视图寻呼机的当前可见片段保留在Base Fragment旁边作为受保护变量。

  3. 如上所述,您可以使用Bas Activity类。

答案 2 :(得分:0)

有3个片段并刷到第3个片段然后再回到第1个片段,第1个片段的数据消失了吗?