代码中:
package com.qianfeng.fragmentdemo;
import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private TextView tv_tab1,tv_tab2,tv_tab3;
private FragmentManager manager;
private FragmentTransaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_tab1=(TextView) findViewById(R.id.tab1);
tv_tab2=(TextView) findViewById(R.id.tab2);
tv_tab3=(TextView) findViewById(R.id.tab3);
tv_tab1.setOnClickListener(this);
tv_tab2.setOnClickListener(this);
tv_tab3.setOnClickListener(this);
manager=getFragmentManager();
transaction=manager.beginTransaction();
transaction.add(R.id.show, new Fragment1());
transaction.commit();
}
@Override
public void onClick(View v) {
transaction=manager.beginTransaction();
switch (v.getId()) {
case R.id.tab1://头条
// transaction.remove(new Fragment1());//删除当前的activtity中的指定的fragment对象
transaction.replace(R.id.show, new Fragment1());//将指定id的区域替换成指定的fragment 先remove再add
break;
case R.id.tab2://社会
transaction.replace(R.id.show, new Fragment2());
break;
case R.id.tab3:
transaction.replace(R.id.show, new Fragment3());
break;
}
transaction.addToBackStack(null);// 将fragment存储到回退栈中进行管理 参数为tag 如果不需要标记就为null
transaction.commit();
}
}
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/tab1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="头条" />
<TextView
android:id="@+id/tab2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="社会" />
<TextView
android:id="@+id/tab3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="娱乐" />
</LinearLayout>
<!-- 存放当前加载内容的fragment-->
<LinearLayout
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
</LinearLayout>