思路
使用Bundle来进行通信
Bundle类用作携带数据,它类似于Map,用于存放key-value名值对形式的值。相对于Map,它提供了各种常用类型的putXxx()/getXxx()方法,如:putString(/getString()和putInt()/getInt(),putXxx()用于往Bundle对象放入数据,getXxx()方法用于从Bundle对象里获取数据。Bundle的内部实际上是使用了HashMap类型的变量来存放putXxx(方法放入的值:
一、示例
1.1、MainActivity.java
package com.example.fragmentmanagers;
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;
import android.widget.Toast;
import java.io.BufferedOutputStream;
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.btn);
button.setOnClickListener(this);
Button button2 = findViewById(R.id.btn_2);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn:
//通信
Bundle bundle = new Bundle();
bundle.putString("message", " love you");
BlankFragment1 bf = new BlankFragment1();
bf.setArguments(bundle);
replaceFragment(bf);
break;
case R.id.btn_2:
replaceFragment(new ItemFragment() );
}
}
// 动态切换fragment
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transation = fragmentManager.beginTransaction();
transation.replace(R.id.framelayout, fragment);
//添加这个表示用了栈
transation.addToBackStack(null);
transation.commit();
}
}
1.2、activity_main.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:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="@string/change"></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_2"
android:text="@string/replace"></Button>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/framelayout"
android:background="@color/colorAccent"></FrameLayout>
</LinearLayout>
1.3、创建Fragement
这里是BlankFragment1.java
,随便创建一个就好
修改生命周期函数onCreate()
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
String string = bundle.getString("message");
Log.d(TAG, "onCreate: " + string);
}
二、测试
点击CHANGE按钮