当我实现类似的东西时,我以一种更好的方式完成了它,在类的意义上。我在一个名为 working 的包中创建了适配器。
下面是代码:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new WorkingFragment();
//You can add as many fragments as you wish here by adding the cases and calling the different fragments.
}
return null;
}
@Override
public int getCount() {
// get item count - equal to number of tabs. 4 is only the number of fragments I had used.
return 4;
}
}
然后您需要在我给出的示例中创建一个名为WorkingFragment 的新类。为了代码简洁,我在主包中创建了这个类。
以下是片段的代码:
public class NewEventFragment extends Fragment {
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//reference the xml file containing the view with all the code here.
}
}
在MainActivity 中,您需要将功能从一个选项卡更改为另一个选项卡。就我而言,我已将其包含在主包中。
下面是 MainActivity 类的代码:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager ViewPager;
private TabsPagerAdapter SectionsPagerAdapter;
private ActionBar actionBar;
//Include the name for the tabs in this array. Make sure the number of elements in this string matches the number of views you will have in your app.
private String[] tabs = {};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialisation
ViewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
SectionsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
ViewPager.setAdapter(SectionsPagerAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
ViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
ViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}
}
希望这有助于您为您的应用实现必要的功能:)