Fragment与Activity通信 Android

导读:
第一种方法:通过handler
第二部分:任务切换

一:通过handler

步骤一:Activity中定义一个方法来设置Handler对象

public Handler communicationHandler;
/*设置*/
public void setHandler(Handler handler)
{
    communicationHandler = handler;
}

步骤二:Fragment中定义Handler,并自己根据情况实现handleMessage方法

/*fragment和activity中均取为同一个名字是自己这样做的,不需要一样*/
public Handler communicationHandler = new Handler()
{
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
        }   
};

步骤三:Fragment在回调函数中,得到所属于的activity,调用Activity的设置handler方法。

/*我的activity名为ClientMainActivity,改成自己的Activity即可*/
ClientMainActivity mainActivity;
public void onAttach(Activity activity) {
        super.onAttach(activity);
        mainActivity = (ClientMainActivity) activity;//得到所属的activity
        mainActivity.setHandler(communicationHandler);//调用设置的activity
    }

设置好后使用Handler传递信息

Activity发送消息

Message msgMessage = new Message();
Bundle bundle = new Bundle();
bundle.putString("type", "temp");  //bundle里放入String
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通信

Activity和Fragment通信

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猎羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值