基本过程:
(1)创建一个待处理的fragment
(2)获取fragmentManger,一般都是通过getSupportFragment()
(3)开启一个事务transaction,一般都是调用fragmentMangerTransaction()
(4)使用transaction进行fragment的替换
(5)事务的提交transaction.commit()方法进行事物的提交
main_activity.xml中的代码:
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();//事物的提交
}
}



