基本过程:
(1)创建一个待处理的fragment
(2)获取fragmentManger,一般都是通过getSupportFragment()
(3)开启一个事务transaction,一般都是调用fragmentMangerTransaction()
? (4)使用transaction进行fragment的替换
(5)事务的提交transaction.commit()方法进行事物的提交
main_activity.xml中的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="改变"
android:textSize="20dp"
android:id="@+id/but1"/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="取代"
android:textSize="20dp"
android:id="@+id/but2"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fram1"
android:background="#0CFFFF"/>
</LinearLayout>
activity中的主要代码:
package com.example.fragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.but1);
button.setOnClickListener(this);
Button button1 = findViewById(R.id.but2);
button1.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.but1:
replaceFragment(new BlankFragment1());
break;
case R.id.but2 :
replaceFragment(new BlankFragment2());
}
}
//动态切换Fragment
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fram1,fragment);
transaction.commit();//事物的提交
}
}
|