본문 바로가기
IT/Android

Android] Fragment 생성시에는 newInstance로.

by 깻잎쌈 2025. 1. 24.
반응형

 

 

All subclasses of Fragment must include a public no-argument constructor.

The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it.

If the no-argument constructor is not available, a runtime exception will occur in some cases during state restore.

 

화면회전이나 화면 재생성으로 인해 Fragment 재생성시 no-argument constructor를 호출하기에,

Fragment 생성할때는 newInstance 사용해서 파라미터 넘기고,

bundle로 값을 저장하고 가져와서 사용한다.

 

 

* <p>It is strongly recommended to supply arguments with {@link #setArguments}
* and later retrieved by the Fragment with {
@link #getArguments}. These arguments
* are automatically saved and restored alongside the Fragment.

https://developer.android.com/reference/android/app/Fragment

 


 

 

 

Fragment 생성시

    public static SampleDialog newInstance(boolean aaa, String bbb) {

        Bundle args = new Bundle();
        args.putBoolean("aaa", aaa);
        args.putString("bbb", bbb);

        SampleDialog fragment = new SampleDialog();
        fragment.setArguments(args);

        return fragment;
    }

 

 

 

Fragment에서 파라미터 값을 사용할때

 getArguments() 사용

 @NonNull
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

       ....
      

        if (getArguments() != null) {
            boolean aaa = getArguments().getBoolean("aaa");
            String bbb = getArguments().getString("bbb");
            
            ...

 

 

Activity에서 호출시

 sampleDialog = SampleDialog.newInstance(false, "sample");
 sampleDialog.show(getSupportFragmentManager(), "SampleDialog");
반응형

댓글