[英]Android: Passing messages from Class to Fragment
I have had a similar question to this not long ago but it wasn't written very well and have also changed my structure. 我不久前也有类似的问题,但是它写得不好,也改变了我的结构。
I am sending messages to a class when buttons are clicked in a fragment. 在片段中单击按钮时,我正在向班级发送消息。 The class in question is MessageInterface (not actually an interface).
有问题的类是MessageInterface(实际上不是接口)。
I now want to send this message off to another fragment, and update some text in there. 我现在想将此消息发送到另一个片段,并在那里更新一些文本。 Here is what I have done so far.
到目前为止,这是我所做的。
This is the MessageInterface class, it successfully receives the message as I proved it with a log. 这是MessageInterface类,正如我用日志证明的那样,它成功接收了消息。
public class MessageInterface {
private String message;
private static MessageInterface instance = new MessageInterface();
private Message msg = new Message();
private Handler handler;
private Bundle bundle;
public MessageInterface() {
}
public static MessageInterface getInstance() {
return instance;
}
public void sendData(final String str) {
bundle = new Bundle();
handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
message = str;
if (!message.isEmpty()){
Log.i("Interface", "Message Revieved in Interface");
bundle.putString("Message", message );
msg.setData(bundle);
handler.sendMessage(msg);
}
}
});
}
public String getData() {
return message;
};
}
And this is the code in the receiving fragment: 这是接收片段中的代码:
private MessageInterface messageInterface = MessageInterface.getInstance();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
super.onActivityCreated(savedInstanceState);
statusText = (TextView) getActivity().findViewById(R.id.statusText);
handler2 = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
statusText.setText((bundle.getString("Message")));
Log.i("Status", "Message Revieved in Status Fragment");
}
};
}
Nothing gets logged here. 什么都没有记录在这里。 The message is not being sent over.
消息未发送出去。
If anyone could give me some tips on how to get this working then great. 如果有人可以给我一些如何使它工作的提示,那就太好了。 I also feel like this isn't the best way to to do it was i might end up with loads of data being sent through here.
我还觉得这不是执行此操作的最佳方法,因为我可能最终会通过此处发送大量数据。
How could I improve it if i can. 如果可以的话,我该如何改善呢?
Thanks. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.