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
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;
}
}
© 2024 OneMinuteCode. All rights reserved.