Android study note 11-Fragments on the user interface (3)

Source: Internet
Author: User

Android study note 11-Fragments on the user interface (3)

How can we manage our Fagment?

To manage Fragments in our Activity, we need to use FragmentManager. We can call the getFragmentManager () method in our Activity to obtain this FragmentManager object.

We can use FragmentManager to do a few things:

1. We can use the findFragmentById or findFragmentByTag method to get the fragments in the Activity;

2. You can use the popBackStack method to simulate the user's rollback button operation and pop up fragments from the rollback stack;

3. Use the addOnBackStackChangedListener () method to register a listener for Stack rollback changes.

How to handle Fragment transactions?

One advantage of using fragment in our Activity is that we can use them to dynamically add, remove, replace, and present some other actions for user interaction. Each of our changes is committed to the Activity as a transaction. We can also save each fragment to the rollback stack managed by the activity, which will cause the user to roll back these fragment changes.

ragmentManager fragmentManager = getFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Each transaction is a series of changes you want to make at the same time. We can set all the changes we want to perform with a given Transaction object. If we want to apply these changes to the activity, we must call the commit () method.

However, before we call the commit method, we may want to call the addToBackStack method to add this transaction to the fragment rollback stack. This rollback stack is managed by the Activity where the fragment is located, allowing you to return to the previous fragment status through the rollback button.

// Create new fragment and transactionFragment newFragment = new ExampleFragment();FragmentTransaction transaction = getFragmentManager().beginTransaction();// Replace whatever is in the fragment_container view with this fragment,// and add the transaction to the back stacktransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();
If we commit multiple changes in a transaction at a time and call the addToBackStack method to save all changes as one transaction to the rollback stack, when we click the back button, multiple changes will be restored at one time.

The order in which we add these changes to FragmentTransaction is irrelevant, except for the following two situations: first, we must call the commit method at last; the second is that if we add multiple fragments to the same container, the order of the fragment we add determines the order in which they are displayed in the view.

If we didn't call the addToBackStack method when removing the fragment transaction, the fragment will be destroyed when we commit it, and the user cannot return this fragment.

Note: we can call the setTransition method to set a transaction animation before each transaction commits the commit method.

The commit method cannot be called to execute these transactions immediately. On the contrary, these transactions are executed in the UI thread of the Activity, when the UI thread can execute these transactions. However, if necessary, we can call the executePendingTransaction method so that the UI thread of our Activity can immediately execute these committed transactions. Do not do this unless the transaction is independent from the work in other threads, which may interrupt other work.

How does Fragment communicate with Activity?

Although Fragment is implemented as an object independent of the Activity, it can be applied to multiple activities, and a given fragment instance can be directly bound to the Activity that contains it.

In special cases, we can call the getActivity method in fragment to access the Activity instance, which is easy to perform some operations, such as obtaining a view component in the activity layout.

View listView = getActivity().findViewById(R.id.list);
Similarly, our Activity can also call methods in Fragment through the reference of fragment in FragmentManager. For example

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
Create an Event Callback Function for the activity

In some cases, we may need a fragment and

For example, if there are two fragement items in an Activity, one is to show article list A and the other is to show article details B. When A user selects an item in an article, fragment A must tell the Activity, and then the Activity notifies fragment B to display the article.

public static class FragmentA extends ListFragment {    ...    // Container Activity must implement this interface    public interface OnArticleSelectedListener {        public void onArticleSelected(Uri articleUri);    }    ...}
Then, the Fragment Activity implements the OnArticleSelectedListener interface and reloads the onArticleSelected method to notify fragmentB of the event in fragmentA. To ensure that the main Activity implements this interface, convert the activity parameter in the onAttach method in Fragment A to OnArticleSelected to instantiate an OnArticleSelected instance.

public static class FragmentA extends ListFragment {    OnArticleSelectedListener mListener;    ...    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        try {            mListener = (OnArticleSelectedListener) activity;        } catch (ClassCastException e) {            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");        }    }    ...}
However, if the main Activity does not implement this interface, a ClassCastException will be thrown in the above method. If the call succeeds, mListener will have reference to the OnArticleSelectedListener interface implemented in the Activity.

public static class FragmentA extends ListFragment {    OnArticleSelectedListener mListener;    ...    @Override    public void onListItemClick(ListView l, View v, int position, long id) {        // Append the clicked item's row ID with the content provider Uri        Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);        // Send the event and Uri to the host activity        mListener.onArticleSelected(noteUri);    }    ...}

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.