使用ActionBar结合fragment实现导航
1,调用ActionBar的setNavigationModel(ActionBar.NAVIGATION_MODE_TABS)设置使用tabs导航
2,调用ActionBar的addTab()添加多个Tab标签
#################承载Fragment的Activity需要实现implements FirstFragment.OnFragmentInteractionListener这个接口,要不然就报错###############第二次碰到这个问题了
代码:包含原来的实现ActionBar中显示View组件(还需要在仔细看一些方法,细节)
1 package com.example.administrator.myapplication; 2 3 import android.net.Uri; 4 import android.support.v4.app.Fragment; 5 import android.support.v4.app.FragmentTransaction; 6 import android.support.v4.view.MenuItemCompat; 7 import android.support.v7.app.ActionBar; 8 import android.support.v7.app.AppCompatActivity; 9 import android.os.Bundle; 10 import android.view.Menu; 11 import android.view.MenuInflater; 12 13 import layout.FirstFragment; 14 15 public class MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener, ActionBar.TabListener { 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_main); 21 22 final ActionBar actionBar = getSupportActionBar(); 23 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 24 //依次添加3个标签 25 actionBar.addTab(actionBar.newTab().setText("first").setTabListener(this)); 26 actionBar.addTab(actionBar.newTab().setText("second").setTabListener(this)); 27 actionBar.addTab(actionBar.newTab().setText("third").setTabListener(this)); 28 29 30 } 31 32 @Override 33 public boolean onCreateOptionsMenu(Menu menu) { 34 MenuInflater inflater = new MenuInflater(this); 35 inflater.inflate(R.menu.menu_main,menu); 36 MenuItemCompat.setShowAsAction(menu.findItem(R.id.search),MenuItemCompat.SHOW_AS_ACTION_ALWAYS); 37 MenuItemCompat.setShowAsAction(menu.findItem(R.id.progess),MenuItemCompat.SHOW_AS_ACTION_ALWAYS); 38 return super.onCreateOptionsMenu(menu); 39 40 41 } 42 43 @Override 44 public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { 45 Fragment fragment = new FirstFragment(); 46 Bundle args = new Bundle(); 47 args.putInt("zhang",tab.getPosition()+1); 48 fragment.setArguments(args); 49 50 android.app.FragmentTransaction ft1 = getFragmentManager().beginTransaction(); 51 ft.replace(R.id.container,fragment); 52 //ft.commit();//这代码不注释掉会保存############################################################################################################ 53 } 54 55 @Override 56 public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { 57 58 } 59 60 @Override 61 public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { 62 63 } 64 65 @Override 66 public void onFragmentInteraction(Uri uri) { 67 68 } 69 }