更新
如果您不使用任何支持库,这应该可以工作
否则你将不得不使用 getSupportActionBar() 和上面提到的依赖项。
试试这样的:
// Get the Instance of the Action Bar, set Navigation Mode, remove title
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
// One tab
actionBar.addTab(actionBar.newTab() .setText("One")
.setTabListener(new TabListener<DemoFragment>(
this, "1", DemoFragment.class)));
// Two tab
actionBar.addTab(actionBar.newTab()
.setText("Two")
.setTabListener(new TabListener<DemoFragment>(
this, "2", DemoFragment.class)));
Edit to Post - 我用于演示的工作代码
这是我使用 Android sdk 14 编写的演示应用程序的代码,就像你一样。
public class MainActivity extends Activity {
// String Titles
static String [] titles = {"Fragment 1", "Fragment 2"};
static String [] fragmentClasses = {Fragment1.class.getName(), Fragment2.class.getName()};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SimpleTabListener.SetUpTabNavigation(this, fragmentClasses, titles);
}
这里是 SimpleTabListener 类
public class SimpleTabListener implements TabListener {
Context m_context;
String m_fragmentClassName ;
Fragment m_fragment = null;
public SimpleTabListener(Context context, String tabFragmentClassName)
{
m_context = context;
m_fragmentClassName = tabFragmentClassName;
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft)
{
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
{
if(m_fragment == null)
{
m_fragment = Fragment.instantiate(m_context, m_fragmentClassName);
ft.add(android.R.id.content, m_fragment);
}else
{
ft.attach(m_fragment);
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
{
// TODO Auto-generated method stub
if(m_fragment != null){
// TODO Auto-generated method stub
ft.detach(m_fragment);
}
}
public static void SetUpTabNavigation(Activity activity, String [] classNames, String [] tabTitles){
ActionBar actionBar = activity.getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener listener;
for(int i = 0; i < tabTitles.length; i++)
{
listener = new SimpleTabListener(activity, classNames[i]);
actionBar.addTab(actionBar.newTab().setText(tabTitles[i]).setTabListener(listener));
}
}
}
Frament1.class
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_1, container, false);
}
}
片段2.class
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment2, container, false);
}
}