[英]Android: passing data from one fragment to another with BroadcastReceiver
I'm trying to send data from a child Fragment
to the parent Fragment
. 我正在尝试将数据从子
Fragment
发送到父Fragment
。 I wrote a code for this, but it doesn't seem to work. 我为此编写了代码,但似乎没有用。
Here's the code so far. 到目前为止,这是代码。 The following one is declared in the sender's side.
在发送方声明了以下内容。
private void sendPINData(String pin) {
Intent broadcastIntent = new Intent("PINData");
broadcastIntent.putExtra(Keys.PIN, pin);
context.sendBroadcast(broadcastIntent);
getFragmentManager().popBackStack();
}
Next, the receiver's side (parent Fragment
) 接下来,接收方(父
Fragment
)
The following line is in the onCreateView()
method. 下一行在
onCreateView()
方法中。
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(localBroadcastReceiver, new IntentFilter("PINData"));
And this one is the BroadcastReceiver
declaration part. 而这就是
BroadcastReceiver
声明部分。
private final BroadcastReceiver localBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent != null) {
pin = intent.getStringExtra(Keys.PIN);
Toast.makeText(context, pin, Toast.LENGTH_SHORT).show();
}
}
};
Here's the code in the parent Fragment
to move to the child Fragment
. 这是父
Fragment
要移到子Fragment
。
PINFragment fragment = new PINFragment();
FragmentTransaction mTransaction = getFragmentManager().beginTransaction();
mTransaction.replace(R.id.main_frame, fragment);
mTransaction.addToBackStack(null);
mTransaction.commit();
You are using local broadcast to be received (in App score only) but you are sending broadcast as global .. I think you should use LocalBroadcastManager.getInstance(Context ctx)
instead of Context
to send braodcast. 您正在使用本地广播来接收广播(仅在App分数中),但是您正在以全局方式发送广播。.我认为您应该使用
LocalBroadcastManager.getInstance(Context ctx)
而不是Context
来发送广播。 see your code updated below: 请参阅下面的代码更新:
private void sendPINData(String pin) {
Intent broadcastIntent = new Intent("PINData");
broadcastIntent.putExtra(Keys.PIN, pin);
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcastIntent);
getFragmentManager().popBackStack();
}
PS dont forget to unregister receiver as well 🙂 PS也不要忘记注销接收器🙂
Good luck,'. 祝好运,'。
private void sendPINData(String pin) {
Intent broadcastIntent = new Intent("PINData");
broadcastIntent.putExtra(Keys.PIN, pin);
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcastIntent);
getFragmentManager().popBackStack();
}
Try this, please! 请尝试一下!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.