我已经创建了一个自定义处理程序,它将负责解雇对话框,显示对话框并显示(自定义)错误消息。但是,我坚持使用自定义错误消息部分。如何发布带有自定义消息的消息&如何在handleMessage中解析它?
现在我在做:
handler.sendMessage(Message.obtain(handler, HANDLER_MESSAGE_ERROR));
我读过关于捆绑的内容,但没有让它发挥作用。最好(保持代码整洁),我想做这样的事情:
handler.sendMessage(Message.obtain(handler, HANDLER_MESSAGE_ERROR, "Custom error message"));
和错误对话框:
handler.sendMessage(Message.obtain(handler, HANDLER_MESSAGE_DIALOG, "Custom title", "Custom error message"));
这是我现在正在使用的处理程序代码:
public class MyHandler extends Handler {
private Activity mContext;
public MyHandler(Activity activity) {
mContext = activity;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyActivity.HANDLER_MESSAGE_ERROR:
try {
Toast.makeText(mContext, "_This should be a custom error message", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
break;
}
}
}
答案 0 :(得分:2)
我使用处理程序传递不同的消息。此代码适用于您。
只传递简单信息:
Message msg = new Message();
msg.what = HANDLER_MESSAGE_ERROR;
Bundle b = new Bundle();
b.putString("message", "Custom error message");
msg.setData(b);
handler.sendMessage(msg);
传递标题和消息:
Message msg = new Message();
msg.what = HANDLER_MESSAGE_DIALOG;
Bundle b = new Bundle();
b.putString("title", "Custom title");
b.putString("message", "Custom error message");
msg.setData(b);
handler.sendMessage(msg);
您将通过以下方式获取方法中的包
@Override
public void handleMessage(Message msg) {
//Get bundle
Bundle b = msg.getData();
String title,messag;
switch (msg.what) {
case MyActivity.HANDLER_MESSAGE_ERROR:
try {
message = b.getString("message");
//show toast here
} catch (Exception e) {
}
break;
case MyActivity.HANDLER_MESSAGE_DIALOG:
try {
title = b.getString("title");
message = b.getString("message");
//show toast here
} catch (Exception e) {
}
break;
}
}
答案 1 :(得分:0)
Message对象可以存储键值对,如下所示:
final Message msg = new Message();
final Bundle data = new Bundle();
data.putString(ERROR, "error message");
msg.setData(data);
在Handler中提取数据包中的数据:
final String e = m.getData().getString(ERROR);