Android fragment several ways to interact with your activity

Source: Internet
Author: User

Here I no longer detail the more conventional way of writing, such as static variables, static methods, persistence, application global variables, sending and receiving broadcasts, and so on.

First, we introduce the use of handler to achieve fragment interaction with the activity.

In the first step, we need to define a method in activity to set the handler object.

 Public void SetHandler (Handler Handler) {  = Handler;}

In the second step, we get fragment activity in the callback function Onattach () in fragment, and call SetHandler method, set handler. The handler is defined in fragment to receive messages that interact with fragment.

@Override Public voidOnattach (activity activity) {Super.onattach (activity); Mactivity=(mainactivity) activity; Mactivity.sethandler (Mhandler);} PublicHandler Mhandler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {Switch(msg.what) { Case 1: Text.settext (String) msg.obj);  Break;                            }  };}; 

We can then send a message in the activity to interact with the Hanlder in fragment.

 Public void Inter (view view) {         new  Message ();          = Edit.gettext (). toString ();          1 ;         Mhandler.sendmessage (msg);}

I wrote a demo to share with you, link address: http://download.csdn.net/detail/huangyabin001/7559807

Click to download Demo

Android fragment several ways to interact with your activity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.