fragment向Activity传数据
先上图
Fragment向activity中传值
1.在Fragment中写一个回调接口
2.在activity中实现这个回调接口
3.在Fragment中onAttach 方法中得到activity中实现好的 实例化接口对象
4.用接口的对象 进行传值
具体代码如下:
MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity implements FragmentTest.SendValue, MyFragment.MySendValue {
private TextView textView;
Button btn_my;
Button btn_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);
btn_my=findViewById(R.id.changeToMy);
btn_test=findViewById(R.id.changeToTest);
btn_my.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.layout_container_fragment,new MyFragment());
fragmentTransaction.commit();
}
});
btn_test.setOnClickLis