The communication between Activity and Fragment in android development

In android,Activity and Fragment are both important UI components that us----programer to program against and users to interact with machine.In other words,Activity and Fragment are the platform of operation of android APP.

So ,there is an important question.how can the two kind of objects communicate with each other?

To begin with,let’s take a look at how to open a Fragment from Activity.

 FragmentManager fragmentManager=getFragmentManager();
 FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();//--------1
  fragmentTransaction.replace(R.id.fragment_container,fragment1);//-------------------2
  fragmentTransaction.commit();//-----------------------------------------------------3

Remember,if you want to open a Fragment after clicking a button,you’d better move the sentence 1,2,3 to the onClickListener block.If you don’t do that,and beginTransaction() only once at the onCreat() method ,after you click the button at the second time,you will get an Exception that “the commit() has been called”.

Since you have opened a Fragment.How to put data to the Fragment?

Well,it’s quite easy,right?Because you have already hold the Fragment’s reference,you can put any data you want to the fragment.
In the Fragment’s Java file ,you can create

public void putArguments(Bundle data)
    {
       bundle=data;
    }

Whenever you want put data,you just invoke the method from Activity Java file.

Since you have known how to put data to a fragment.How to put data back to Activity?

From the perspective of philosophy,if you want communicate with a subject,you have to know the subject.Here,the first problem we have to solve is how to get the reference of the Activity.
Well,we can use

getActivity();

This method is useful.It returns back the reference of the Activity that the Fragment depends on.
You know what to do next,right?

((MainActivity)getActivity());

cast the type from top to bottom.This is agreed by Java,because the process is just

MainActivity-----(getActivity)------>Activity------((MainActivity)getActivity)---->MainActivity

Now,you can get whatever you want through the reference of MainActivity!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值