Passing custom Fragment class specific parameters that inherit Fragment

The custom Fragment class of inherited Fragment, CustomFragment, cannot be passed by modifying the construction method like the custom Activity class of inherited Activity. So we need to implement it through bundle and instance.
There are four steps:
1. Create a global variable corresponding to the parameter for use.
2. The newinstance initializes the Fragment, passing the parameter and Bundle through the method.
3. Assign the parameters passed in by Bundle to global variables when initializing Fragment.
4. When I need to use the corresponding parameter data, I can use it by calling the global variable of the corresponding parameter.

public class CustomFragmentextends Fragment {
//1. Create a global variable corresponding to the parameter to use
    @LayoutRes
    private int sampleLayoutRes;
    @LayoutRes
    private int practiceLayoutRes;

//2. The newinstance initializes the Fragment, passing the parameter and Bundle through the method.
    public static  CustomFragment newInstance(@LayoutRes int sampleLayoutRes,@LayoutRes int practiceLayoutRes){
        CustomFragment fragment = new CustomFragment();
        Bundle args = new Bundle();
        args.putInt("sampleLayoutRes",sampleLayoutRes);
        args.putInt("practiceLayoutRes",practiceLayoutRes);
        fragment.setArguments(args);
        return  fragment;
    }

//3. Assign the parameters passed in by Bundle to global variables when initializing Fragment.
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if(null != args){
            sampleLayoutRes = args.getInt("sampleLayoutRes");
            practiceLayoutRes = args.getInt("practiceLayoutRes");
        }
    }

//4. When I need to use the corresponding parameter data, I can use it by calling the global variable of the corresponding parameter.
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_page,container,false);

        ViewStub sampleStub = (ViewStub) view.findViewById(R.id.sampleStub);
        sampleStub.setLayoutResource(sampleLayoutRes);
        sampleStub.inflate();

        ViewStub practiceStub = (ViewStub) view.findViewById(R.id.practiceStub);
        practiceStub.setLayoutResource(practiceLayoutRes);
        practiceStub.inflate();
        return view;
    }
}

When you call CustomFragment in activity, you can pass parameters when you create the CustomFragment object.

PageFragment.newInstance(R.layout.sample_color, R.layout.practice_color)

Keywords: Fragment

Added by walexman on Fri, 01 May 2020 20:16:25 +0300