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");
'IT > Android' 카테고리의 다른 글
Android] 안드로이드 스튜디오 미사용 코드 제거 (0) | 2024.09.08 |
---|---|
Android] PreviewView Pinch Zoom (0) | 2024.08.22 |
Android] 안드로이드 프로젝트 패키지명 변경하기 (0) | 2024.06.23 |
Android] 파일 용량 / bitmap 용량 구하기 (0) | 2024.03.22 |
Android] gradle ndk.adbfilters 오류 수정 (0) | 2023.11.12 |
댓글