具有ViewPager的工具栏无法恢复开始新活动时选择的最后一个标签

时间:2015-10-13 23:18:53

标签: android tabs android-toolbar

我正在使用v7小部件工具栏并将其设置为我的AppCompatAcivity中的支持操作栏。当我在其他标签页上开展新活动时,我无法使用onSaveInstanceState恢复我上次使用的标签。 onCreate的savedInstanceState将为null,并且当使用制表符从活动2到我的活动时,永远不会调用onRestoreInstanceState。我该如何解决这个问题?

public class ContactsActivity extends AppCompatActivity {

    private static String TAB_POSITION = "POSITION";

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        toolbar.setNavigationIcon(R.drawable.logo_spokeo);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new RecentContactsFragment(), "Recent Contacts");
        adapter.addFragment(new AddressBookFragment(), "Address Book");
        adapter.addFragment(new RecentContactsFragment(), "Settings");
        viewPager.setAdapter(adapter);

        if (savedInstanceState != null) {
            viewPager.setCurrentItem(savedInstanceState.getInt(TAB_POSITION, 0), false);
        }


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(TAB_POSITION, tabLayout.getSelectedTabPosition());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        viewPager.setCurrentItem(savedInstanceState.getInt(TAB_POSITION), true);
    }
}

0 个答案:

没有答案