Fragment与Activity交互(使用Handler)

1.在Activity中定义一个方法用来设置Handler对象

public void setHandler(Handler handler) {
mHandler = handler;
}

2.在Fragment中的回调函数onAttach()中得到Fragment所在的Activity,并调用setHandler方法,设置Handler。该Handler在Fragment中定义,用来接收来自Activity的消息

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = (MainActivity) activity;
mActivity.setHandler(mHandler);
}

public Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
text.setText((String) msg.obj);
break;
}
};

};

3.在Activity发送消息给Fragment的Handler

Message msg = new Message();

mHandler.sendMessage(msg);

上一篇:Springboot中mybatis执行逻辑源码分析


下一篇:loadrunner中组合场景的应用