导读: 第一种方法:通过handler 第二部分:任务切换 |
步骤一:Activity中定义一个方法来设置Handler对象 |
public Handler communicationHandler;
public void setHandler(Handler handler)
{
communicationHandler = handler;
}
步骤二:Fragment中定义Handler,并自己根据情况实现handleMessage方法 |
public Handler communicationHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
步骤三:Fragment在回调函数中,得到所属于的activity,调用Activity的设置handler方法。 |
ClientMainActivity mainActivity;
public void onAttach(Activity activity) {
super.onAttach(activity);
mainActivity = (ClientMainActivity) activity;
mainActivity.setHandler(communicationHandler);
}
Activity发送消息
Message msgMessage = new Message();
Bundle bundle = new Bundle();
bundle.putString("type", "temp");
msgMessage.setData(bundle);
communicationHandler.sendMessage(msgMessage);
Fragment中接收消息
public Handler communicationHandler = new Handler()
{
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
String typeString = bundle.getString("type");
if(typeString.equals("temp"))
{
temp_value.setText(bundle.getString("temp"));
}
else if(typeString.equals("humi"))
{
humi_value.setText(bundle.getString("humi"));
}
}
};
Activity和Fragment通信