Android learning route (23) build a dynamic UI using Fragment-communication between Fragment and androidfragment

Source: Internet
Author: User

Android learning route (23) build a dynamic UI using Fragment-communication between Fragment and androidfragment

Position first. Next Translation: p

In order to reuse the Fragment UI components, you should build each as a completely self-contained, modular component that defines its own layout and behavior. once you have defined these reusable Fragments, you can associate them with an Activity and connect them with the application logic to realize the overall composite UI.

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. all Fragment-to-Fragment communication is done through the associated Activity. two Fragments shoshould never communicate directly.

Define an Interface

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. the Fragment captures the interface implementation during its onAttach () lifecycle method and can then call the Interface methods in order to communicate with the Activity.

Here is an example of Fragment to Activity communication:

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 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 the fragment can deliver messages to the activity by callingonArticleSelected()Method (or other methods in the interface) usingmCallbackInstance ofOnHeadlineSelectedListenerInterface.

For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.

    @Override    public void onListItemClick(ListView l, View v, int position, long id) {        // Send the event to the host activity        mCallback.onArticleSelected(position);    }
Implement the Interface

In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in the fragment class.

For example, the following activity implements the interface from the above 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    }}
Deliver a Message to a Fragment

The host activity can deliver messages to a fragment by capturingFragmentInstancefindFragmentById(), Then directly call the fragment's public methods.

For instance, imagine that the activity shown above may contain in another fragment that's used to display the item specified by the data returned in the above callback method. in this case, the activity can pass the information already ed in the callback method to the other fragment that will display the item:

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        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 = new ArticleFragment();            Bundle args = new Bundle();            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();        }    }}

How does Android Fragment be added to a LinearLayout? How can I use Fragment? The more detailed, the better.

If the supportv4 compatibility package is used for a relatively low version
Fragment labels cannot be used in Layout
It is best to write a framelayout label in the layout with an xml file.

Write a subclass to inherit Fragment.

Use Fragment in FragmentActivity. BIND. Add. Remove .. In this case, bind the id of the Framelayout component.

To execute the operation, you need to get the FragmentManager and submit the transaction through FragmentTransaction.

This is the same as the official demo.

Note that it is best not to create a new Fragment somewhere else. The lifecycle of Fragment is affected by related activities .. It is best to define the static newInstance method in yourself.

Hope to help you.

Problems with Fragment in Android programming

Replace fragment in framelayout.

Related Article

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.