package tab.test; import com.example.actionbar_tab.R; import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.os.Bundle; @SuppressWarnings("deprecation")
public class ActionBarTab extends Activity implements ActionBar.TabListener { private ActionBar ab = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
this.setContentView(R.layout.main_layout);
ab = this.getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//---------------------------------------------------
ab.addTab(ab.newTab().setText("第一页").setTabListener(this));
ab.addTab(ab.newTab().setText("第二页").setTabListener(this));
ab.addTab(ab.newTab().setText("第三页").setTabListener(this)); super.onCreate(savedInstanceState);
}
//-------------------------------------------------------------
//Avtivity实例状态恢复方法
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if(savedInstanceState.containsKey("items")){
ab.setSelectedNavigationItem(savedInstanceState.getInt("items"));
}
super.onRestoreInstanceState(savedInstanceState);
}
//Avtivity实例状态保存方法
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("items", ab.getSelectedNavigationIndex());
super.onSaveInstanceState(outState);
}
//--------------------------------------------------------------
@Override
public void onTabReselected(Tab tab, FragmentTransaction fter) { } @Override
public void onTabSelected(Tab tab, FragmentTransaction fts) {
//--------------------
Bundle tab_info = new Bundle();
tab_info.putInt("items", tab.getPosition()+1);
Fragment fragment = new Tab_Fragment();
fragment.setArguments(tab_info);
//--------------------
FragmentTransaction ft = this.getFragmentManager().beginTransaction();
ft.replace(R.id.my_content, fragment);
ft.commit();
} @Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub } }
xml:
//fragment_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/my_text"
android:background="#009eff"
android:gravity="center_vertical|center_horizontal"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Fragment"
android:textSize="100sp"
android:textColor="#FFFFFF"/> </LinearLayout>
//main_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_content"
android:background="#666"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > </LinearLayout>