使用add与hide切换fragment
首先,在activity中添加方法(参数fragment是将要切换的fragment,变量mcContent是用来区分当前fragment和将要切换的fragment的)
public void switchFm(BaseFragment fragment) {
if (fragment != mContent) {
FragmentTransaction ft = fm.beginTransaction();
if (fragment.isAdded()) {
ft.hide(mContent).show(fragment).commit();
} else {
if (mContent == null) {
ft.add(R.id.fl_content, fragment).commit();
} else {
ft.hide(mContent).add(R.id.fl_content, fragment).commit();
}
}
mContent = fragment;
}
}
在activity中调用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
RadioGroup rgHelloworld = (RadioGroup) findViewById(R.id.rg_helloworld);
rgHelloworld.setOnCheckedChangeListener(this);
rgHelloworld.check(R.id.hello);
}
切换方法(实现RadioGroup的OnCheckedChangeListener监听):
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedID) {
switch (checkedID) {
case R.id.hello:
switchFm(new HelloFragment());
break;
case R.id.world:
switchFm(new WorldFragment());
break;
}
}
由此就可以自如的切换fragment
附xml文件:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fl_top_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kang.fragmentdemo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#4250a7">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textColor="#ffffff"
android:textSize="22sp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<FrameLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="@+id/rg_helloworld"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_gravity="bottom"
android:orientation="horizontal">
<RadioButton
android:id="@+id/hello"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/bg_radiobutton"
android:button="@null"
android:gravity="center"
android:text="hello"
android:textColor="#ffffff" />
<RadioButton
android:id="@+id/world"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/bg_radiobutton"
android:button="@null"
android:gravity="center"
android:text="world"
android:textColor="#ffffff" />
</RadioGroup>
</FrameLayout>
</LinearLayout>
</FrameLayout>
附效果图: