一,Activity 布局为
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.jiangtunjf.jgapplication.Main9Activity">
<Button
android:text="显示1"
android:onClick="onTestTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="显示2"
android:onClick="onTestTwo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="显示3"
android:onClick="onTestTwo3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="隐藏1"
android:onClick="onTestTwo4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="隐藏2"
android:onClick="onTestTwo5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="隐藏3"
android:onClick="onTestTwo6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="@+id/flly_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
二,Activity 代码为
public class Main10Activity extends AppCompatActivity {
private FrameLayout mFrameLayoutContent;
private TestFragment mTestFragment;
private TestFragment2 mTestFragment2;
private TestFragment3 mTestFragment3;
private FragmentManager mSupportFragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main10);
mFrameLayoutContent = findViewById(R.id.flly_content);
mSupportFragmentManager = getSupportFragmentManager();
mTestFragment = new TestFragment();
mTestFragment2 = new TestFragment2();
mTestFragment3 = new TestFragment3();
init();
}
/**
* 初始化操作
*/
private void init() {
mSupportFragmentManager.beginTransaction()
.add(R.id.flly_content, mTestFragment, mTestFragment.getClass().getSimpleName())
.add(R.id.flly_content, mTestFragment2, mTestFragment2.getClass().getSimpleName())
.add(R.id.flly_content, mTestFragment3, mTestFragment3.getClass().getSimpleName())
.commit();
}
public void onTestTwo(View view) {
LogUtils.d("onTestTwo");
mSupportFragmentManager.beginTransaction()
.show(mTestFragment)
.commit();
}
public void onTestTwo2(View view) {
mSupportFragmentManager.beginTransaction()
.show(mTestFragment2)
.commit();
}
public void onTestTwo3(View view) {
mSupportFragmentManager.beginTransaction()
.show(mTestFragment3)
.commit();
}
public void onTestTwo4(View view) {
mSupportFragmentManager.beginTransaction()
.hide(mTestFragment)
.commit();
}
public void onTestTwo5(View view) {
mSupportFragmentManager.beginTransaction()
.remove(mTestFragment2)
.commit();
}
public void onTestTwo6(View view) {
mSupportFragmentManager.beginTransaction()
.remove(mTestFragment3)
.commit();
}
}
三,效果图