Android pass values to Fragment

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u014619545/article/details/90717094
Android in many ways to traditional values, there Intent with argument constructor, interface based, etc., each of the methods are useful in various usage scenarios. This introduces the next through the setArguments () method to the traditional values ​​of the Fragment.
Fragment in Android application is very wide, can be used when a new object via direct configuration with no parameters. So why can not we have directly participate in the new structure when the parameters are passed directly to the past? Tried this method should know, Fragment is not allowed to participate presence of its internal structure. Otherwise it will throw the following exception.

Here Insert Picture Description

The reason is that at the time of the destruction of Fragment rebuild its internal bottom will only call its constructor with no arguments, there are parameters which led to the loss of data in some unusual circumstances. When we use the Fragment by value, more recommended setArguments () to transmit data. Use as follows:
    //可省略
    public CouponInstanceFragment() {
    }

    public static CouponInstanceFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString("key", url);
        CouponInstanceFragment fragment = new CouponInstanceFragment();
        fragment.setArguments(args);
        return fragment;
    }
When using the transmission parameters and creates an object, corresponding to the following methods:
CouponInstanceFragment fragment=CouponInstanceFragment.newInstance(CouponStatus.UNUSE)

While values ​​can () acquired by the onViewCreated Fragment getArgument () of.

getArguments().getString("key");

As can be seen from the above few lines of code, we are actually to carry parameters by creating a Bundle object when passed by value, but it should be noted that the bundle of transfer value is limited in size, and in about 1M, will exceed after throwing abnormal.

Guess you like

Origin blog.csdn.net/u014619545/article/details/90717094