API 21 setSelectedNavigationItem和addTab是否已弃用?

时间:2014-12-17 17:43:10

标签: java android android-fragments tabs android-5.0-lollipop

我对Android编程比较陌生,我遇到了与API 21有关的问题。下面的代码工作得很好。但是当我更新到API 21时,不推荐使用setSelectedNavigationItem和addTab。我已经阅读了相当多的关于这个问题的内容并看到了一些很好的例子,但我仍然能够理解它。任何帮助将非常感谢。感谢

JAVA CODE:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

ActionBar actionBar;
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
    actionBar = getActionBar();
    assert actionBar != null;
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab tab1 = actionBar.newTab();
    tab1.setText("TAB1");
    tab1.setTabListener(this);

    ActionBar.Tab tab2 = actionBar.newTab();
    tab2.setText("TAB2");
    tab2.setTabListener(this);

    actionBar.addTab(tab1);
    actionBar.addTab(tab2);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}

@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;
}

class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;
    if (position == 0) {
        fragment = new FragmentA();
    }
    if (position == 1) {
        fragment = new FragmentB();
    }
    return fragment;
}

@Override
public int getCount() {
    return 2;
}

我的一个碎片:

public class FragmentB extends Fragment {

public FragmentB() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_b, container, false);
}

}

0 个答案:

没有答案