android中ActionBar +Fragment

/**
* 测试tab标题栏
*
* @time 下午03:34:16
* @author zhenhuayue
* @Email [email protected]
*/
public class ActionBarDemoActivity extends Activity implements TabListener {
FirstFragment firstFragment = null;
SecondFragment secondFragment = null;
ThirdFragment thirdFragment = null;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
// 取得actionBar
ActionBar actionBar = getActionBar();
// actionBar.setCustomView(view, layoutParams)
// 添加tag标签页
actionBar.addTab(actionBar.newTab().setText("测试一").setTabListener(this).setTag(1));
actionBar.addTab(actionBar.newTab().setText("测试二").setTabListener(this).setTag(2));
actionBar.addTab(actionBar.newTab().setText("测试三").setTabListener(this).setTag(3));


actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}


/**
* 初始化方法
*/
private void init() {
firstFragment = new FirstFragment();
secondFragment = new SecondFragment();
thirdFragment = new ThirdFragment();
}


@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// 为Fragment设置淡入淡出效果
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);


switch ((Integer) tab.getTag()) {
case 1:
if (firstFragment.isHidden()) {
ft.show(firstFragment);
Log.e("tag", "show1");
} else {
ft.hide(firstFragment);
Log.e("tag", "hide1");
}


break;
case 2:
ft.show(secondFragment);
Log.e("tag", "show2");
break;
case 3:
ft.show(thirdFragment);
Log.e("tag", "show3");
break;
}
}


@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
switch ((Integer) tab.getTag()) {
case 1:
ft.hide(firstFragment);
Log.e("tag", "hide1");
break;
case 2:
ft.hide(secondFragment);
Log.e("tag", "hide2");
break;
case 3:
ft.hide(thirdFragment);
Log.e("tag", "hide3");
break;
}


}


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


}

}

 

 

/**
* 碎片文件一
*
* @time 下午05:16:14
* @author zhenhuayue
* @Email [email protected]
*/
public class FirstFragment extends Fragment {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.firstfragment, container, false);
registerForContextMenu(root.findViewById(R.id.txv_first));
return root;
}


@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(Menu.NONE, 0, Menu.NONE, "菜单1");
menu.add(Menu.NONE, 1, Menu.NONE, "菜单2");
}


@Override
public boolean onContextItemSelected(MenuItem item) {
return super.onContextItemSelected(item);
}


}

你可能感兴趣的:(android)