How do I resolve the error Avoid non-default constructs in fragments?

Asked 2 years ago, Updated 2 years ago, 31 views

Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead

There is this error, but when I searched on Google, I heard that if you make a constructor that receives a certain value other than the default constructor while using the fragment, you will get this error. You need a way to pass the value from the activity to the fragment.

android

2022-09-22 21:41

1 Answers

When creating a project, it is common to call the setArgument() function by placing the parameters in the Bundle at creation without overloading the constructor. Because when a fragment is restored by Android, it invokes the default constructor of the fragment, so the overloaded constructor is not guaranteed.

Please refer to the following code. The idiomatic code used to create the fragment. (https://developer.android.com/reference/android/app/Fragment.html)

public static class DetailsFragment extends Fragment {
    /**
     * * Create a new instance of DetailsFragment, initialized to
     * * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        text.setText(String.valueOf(getShownIndex()));
        return textView;
    }   
}


2022-09-22 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.