directory


  • Encapsulates the BaseFragment base class
  • Use the static factory method newInstance(…) To get the Fragment instance
  • The Fragment status is saved or recovered onsite
  • Avoid overlapping views in fragments caused by incorrect operations
  • Avoid Fragment crashes due to asynchronous operations (to be added tomorrow 22nd Jan, this is a bug I encountered when adapting tablets in my project)
  • Fragment listens for return events for virtual and physical keys

  • Use a maximized DialogFragment to implement a floating hierarchy view
  • Determine whether a page should be Fragment or Activity

——————————


The 2015-01-22″


Updated a tip on how to listen for return key events in fragments, which I think is the best way so far.

What I answered were some basic and common ones, so I didn’t involve some deep questions. Look at the other answers, some of them are very good.

I also mentioned at the end of the answer whether to use Fragment or Activity in business scenarios. The three sub-projects I have participated in (including N projects I have never participated in, and I have seen the source code in the previous code review) basically use a large amount of Fragment to do view. Assembly is more flexible.

Our video document component development is also based on fragments. When we access the project, we only need to reserve the Layout, and then the component will fill the Layout in the form of fragments.

Fragment+Activity does not mean that there must be only one Activity. Our project is divided into LoginActivity, SplashActivity, and HomeActivity. See my final answer.

Therefore, I think it is beyond doubt whether to use it or not. We should not deny the convenience of learning something just because it costs a lot to learn and needs more attention.

Fragment also has some pits, which I have encountered in the project, and I will add them tomorrow.

Thanks @bowl bowl supplement

add
@ noodlesThe answer view overlaps because the fragment has a memory leak.


The creation and destruction of activities are hosted entirely in SystemServer (AMS), whereas fragments are manually created and added to SystemServer, so there is a problem.



The Fragment life cycle starts at add and ends at Remove. No matter how the app changes, crashes, or processes are reclaimed, as long as there is no Remove, the Android framework will automatically create and restore the fragment state.


—————————————————


The 2015-01-22 15:20


I was on my way out to pick up my girlfriend, and I got 200 likes.

Comment in ask pack good have no, I person all in Chongqing, sf express little elder brother very quick of good? ! Remember, remember. Blue, I spent a day cleaning at home today, mopping the floor, cleaning the floor, cleaning the table, cleaning up a load of garbage I brought back from Fuzhou, went downstairs to collect a express delivery, went downstairs to the property to take a bucket of oil delivery, and then washed all kinds of clothes. From next week, I will cook dinner for my girlfriend every day (if I am alone, I can order take-out).

So you have girlfriend has not married to think naked resignation friends can be considered clearly, my girlfriend to my father-in-law said I naked resignation, father-in-law did not talk at that time (. · ω´ ·).

In the evening, I will probably supplement a little Fragment and use other small skills. They are all useful things I have encountered in my work. They are more suitable for novices.

Try to write this answer well enough to live up to the 200 likes.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — thank invited, I was in the pack, see to answer an answer to this problem.

First of all, the convenience brought by Fragment is enough to make us ignore the troubles it may cause, and many of the troubles are caused by incorrect use methods.

After all, creating a Fragment requires fewer system resources than an Activity, yet has more flexible control.

The project I participated in basically did not use Activity to do UI display, and this part of responsibility was transferred to Fragment to achieve.

Fragments are generally divided into two types. One type is a Fragment with A UI, which can be displayed as a page or View, and the other type is a Fragment without a UI, which is generally used to save data.

As for the overlap mentioned by the topic and the problem of creating multiple fragments, they are all caused by their own improper use. You need to get the correct method of using fragments.

Okay, that’s enough. I have to pack my monitor, and I’m late for the delivery.

There is time to replenish.

— — — — — — — — — — — — — — — — — — line — — — — — — — — — — — — — — — — — — — — — — — finished packing, express little elder brother hasn’t come yet, it’s starting to rain again… Let me write it down.

For example, to instantiate a View, abstract a getLayoutId method. The subclass does not care about creating the View. You can also provide an afterCreate abstract function that is called after initialization. Subclasses can perform initialization operations. You can also add common methods to the base class, such as ShowToast().


 public abstract class BaseFragment extends Fragment {
    protected View mRootView;

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(null == mRootView){
           mRootView = inflater.inflate(getLayoutId(), container, false);
        }
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        afterCreate(savedInstanceState);
    }

protected abstract int getLayoutId();

    protected abstract void afterCreate(Bundle savedInstanceState);
}
Copy the code


Thank you
@xiaoxiao MiAdded, modified


But one thing is, it’s better to check that your mRootView is null re-inflate before you go back in this public View onCreateView method, because in ViewPager this method is called multiple times as the page slides, Inflate over, you just use it.


  • Use the static factory method newInstance(…) To get the Fragment instance

This can be found in Google code. The advantage is that it takes the exact parameters and returns an instance of the Fragment. It avoids the problem of not knowing the required parameters outside the class when creating the Fragment, which is especially useful in collaborative development.

Also, Fragment recommends using setArguments to pass parameters, so that the Fragment can’t automatically call its own no-argument constructor when the pictureschange and lose data.

public static WeatherFragment newInstance(String cityName) {
    Bundle args = new Bundle();
    args.putString(cityName,"cityName");
    WeatherFragment fragment = new WeatherFragment();
    fragment.setArguments(args);
    return fragment;
}
Copy the code


Don’t save ViewState in fragments!


Don’t save ViewState in fragments!


Don’t save ViewState in fragments!

For more clarity and stability in your code, it is best to distinguish between fragment state preservation and View state preservation. If a property belongs to a view, do not save its state in the fragment unless the property belongs to the Fragment.

Each custom View is obligated to save state. Like EditText, you can set a switch to save or not, for example: Android :freezeText=”true/false”.

public class CustomView extends View { ... @Override public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); Return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { super.onRestoreInstanceState(state); // Restore the saved state}... }Copy the code

Handles fragment state saving, such as data retrieved from the server.

    private String serverData;
     
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("data", serverData);
    }
 
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        serverData = savedInstanceState.getString("data");
    }
Copy the code


If you add or replace a Fragment that contains a TAG, the Fragment will be replaced with the same TAG.


public class WeatherFragment extends Fragment {
    //TAG
    public static final String TAG = WeatherFragment.class.getSimpleName();
Copy the code


For maximum reuse, check whether savedInstanceState is not empty in the Activity’s onCreate(Bundle savedInstanceState);

Is not null, use first getSupportFragmentManager () findFragmentByTag () find it, find the instance doesn’t have to create again.

WeatherFragment fragment = null; if(savedInstanceState! =null){ fragment = getSupportFragmentManager().findFragmentByTag(WeatherFragment.TAG); } if(fragment == null){ fragment = WeatherFragment.newInstance(...) ; }Copy the code


  • Fragment listens for return events for virtual and physical keys

I’ve seen a lot of methods, but this one is the best, set an OnKeyListener to the rootView to listen for key events


mRootView.setFocusable(true); mRootView.setFocusableInTouchMode(true); mRootView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) {if (keyCode == keyevent.keycode_back) {// It's not necessary to trigger the return stack, you can do some other things, I'm just giving you an example. getActivity().onBackPressed(); return true; } return false; }});Copy the code


  • Use a maximized DialogFragment to implement a floating hierarchy view

If you have a list page, such as Zhihu, click Item to open the details page, you can use the maximum DialogFragment to display the details page, and you don’t need to provide a specific ContainerId to display the details page, because the details page usually fills up the screen on the Phone. Use DialogFragment.

This is not the best approach, however, when considering Tablet adaptation, as shown in the figure below



On a Tablet, it’s embedded. On a phone, it’s full space.

At this point, you can implement the detail page with only fragments to meet the needs of embedding Tablet devices. You can use full-screen DialogFragment to wrap the Fragment on mobile phones, and then just need dialogFragment.show (…). Can.

As you can see, the use of fragments is very flexible.

  • Determine whether a page should be Fragment or Activity

If the latter page does not need much data from the previous page, it is recommended to display it as an Activity, otherwise it is better to use a Fragment (although this is not always the case).

For example, SplashActivity and MainActivity don’t have much coupling and can be split into two activities.

These are just a few ways to use fragments, but they satisfy common development needs.

In fact, I did not encounter any of these problems during my stay in the project, so I naturally dealt with them in the way of my colleagues. I got a lot of things that I did not know before, but if you encounter them, you can search them on Baidu and find a lot of them, but few of them are really useful, and all of them are copied from each other.

Another reason is that most people in China don’t have the energy, time or inclination to do original sharing.

Fragment is a very basic thing and will be available after 3.0. Is it difficult? It is not difficult, is to pay attention to a lot of points, with a lot of nature will know.