安卓第六天---Fragment之间的信息传递

本文所使用的传值方法时利用接口回调来实现两个Fragment之间的相互传值的.
首先,先创建一个接口:

//这就是接口中的代码,非常简单
public interface SetTextSecond {
public void setText(String s);
}

其次就是在FirstFragment中编写为SecondFragment的信息了

private EditText message;
private Button send;
//设置回调接口
private SetTextSecond setTextSecond;

@Nullable
@Override
 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.first_frgment,container,false);
    //在Fragment里面查找到布局里面的控件,得在findViewByID前边加上前缀变成View.findViewByID,这样就可以进行控件的操作了
    message = view.findViewById(R.id.message);
    send = view.findViewById(R.id.send_button);
	//message控件为EditText,send为Button
	//在点击send时,获取message中的信息,然后将信息传入接口中,设置值
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String messageText = message.getText().toString().trim();
            if (setTextSecond != null){
                setTextSecond.setText(messageText);
            }
        }
    });

    return view;
}
    //在ONAttach中,Fragment就能获得Activity,在实现SetTextSecond这个回调接口的Activity内,就能实现回调机制
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof SetTextSecond){
        setTextSecond = (SetTextSecond) context;
    }
}

下面是主函数中的方法
这里的secondFragment只能设置成全局变量,并在onCreate()方法中进行实现.
secondFragment是设置为全局变量的!

 @Override
 public void setText(String s) {  
  	TextView textView = secondFragment.getView().findViewById(R.id.received);
    textView.setText(s);
}

到这里,就可以实现通过Fragment回调方法来进行传值!
下面是没有传值的显示
在这里插入图片描述

设置参数:
在这里插入图片描述
点击发送之后,的成功页面!
在这里插入图片描述

到此结束Fragment之间的参数传递!
布局参照上一个博客!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值