Communication between Android training and fragment

Source: Internet
Author: User

This article translated from: http://developer.android.com/training/basics/fragments/communicating.html

To reuse the fragment UI components, each fragment you create should be a self-contained modular component with its own layout and behavior. Once you define reusable fragment, You can associate them with an activity and connect them to the application logic to implement all the combined UIS.

You often want a fragment to communicate with another fragment. For example, you need to change the content based on a user event. Communication between all fragment is completed through the associated activity. Another fragment should not communicate directly.

Interface Definition

To allow fragment to communicate with its activity, you can define an interface in the fragment class and implement it in the activity to which it belongs. Fragment captures the implementation of this interface during its onattach () method execution, and then it can call the interface method to communicate with the activity.

The following is an example of communication between fragment and activity:

Public class headlinesfragment extends listfragment {


Onheadlineselectedlistener mcallback;

 


// Container activity must implement this interface


Public interface onheadlineselectedlistener {


Public void onarticleselected (INT position );


}

 


@ Override


Public void onattach (activity ){


Super. onattach (activity );



// This makes sure that the container activity has implemented


// The callback interface. If not, it throws an exception


Try {


Mcallback = (onheadlineselectedlistener) activity;


} Catch (classcastexception e ){


Throw new classcastexception (activity. tostring ()


+ "Must implement onheadlineselectedlistener ");


}


}



...

}

Now, this fragment can send messages to the activity by calling the onhealdlineselectedlistener method (or the method in other interfaces) of mcallback.

For example, the following method in fragment is called when the user clicks the list item. This fragment uses the callback interface to send the event to its parent activity.


@ Override


Public void onlistitemclick (listview L, view V, int position, long ID ){


// Send the event to the host activity


Mcallback. onarticleselected (position );

}

Implementation Interface

To receive Event Callback from fragment, its parent activity must implement the interface defined in the fragment class.

For example, the following activity implements the interface defined in the preceding example:

Public static class mainactivity extends Activity


Implements headlinesfragment. onheadlineselectedlistener {


...



Public void onarticleselected (INT position ){


// The user selected the headline of an article from the headlinesfragment


// Do something here to display that article


}

}

 

Send a message to a fragment

Capture the fragment instance by using the findfragmentbyid () method. The parent activity can send messages to the fragment and then directly call the public method of the fragment.

For example, assume that the activity shown above contains another fragment used to display the specific project data returned in the preceding callback method. In this case, the activity can pass the received information in the callback Method to the fragment that displays the project:

publicstaticclassMainActivityextendsActivity
        implementsHeadlinesFragment.OnHeadlineSelectedListener{
    ...
 
    publicvoid onArticleSelected(int position){
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
 
        ArticleFragment articleFrag =(ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);
 
        if(articleFrag !=null){
            // If article frag is available, we're in two-pane layout...
 
            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        }else{
            // Otherwise, we're in the one-pane layout and must swap frags...
 
            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment =newArticleFragment();
            Bundle args =newBundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
        
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
 
            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);
 
            // Commit the transaction
            transaction.commit();
        }
    }
}

 

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.