1.设置MainActivity布局:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/container">
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tab1"
android:layout_weight="1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="tab2" />
</LinearLayout>
其中framelayout作为显示fragment的容器.两个按钮用来切换不同的fragment。
2.定义Fragment子类,需继承android.app.Fragment类
此次需注意,android.app.Fragment只支持api11以上的版本,如果要兼容低版本,需使用android.supportv4.app.Fragment类,并且用法也略有区别。
Fragment1.java:
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1,container, false);
}
}
Fragment2.java:
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2,container, false);
}
}
注意,在onCreateView方法中指定布局文件。布局文件此处略。
3.设置MainAcitivity
package com.example.fragmenttest;
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
public class MainActivity extends Activity {
Button btn1;
Button btn2;
Fragment f1;
Fragment f2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
if (f2!=null) {
transaction.hide(f2);
}
if (f1==null) {
f1= new Fragment1();
transaction.add(R.id.container, f1);
} else {
transaction.show(f1);
}
transaction.commit();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
if (f1!=null) {
transaction.hide(f1);
}
if (f2==null) {
f2= new Fragment2();
transaction.add(R.id.container, f2);
} else {
transaction.show(f2);
}
transaction.commit();
}
});
}
}
此处注意, 需开启事物来管理fragment,并提交事物