안드로이드
프래그먼트 사용 시 주의사항
홍규홍규
2018. 7. 24. 14:28
- 프래그먼트의 추가 또는 변경이 필요하면 그 때마다 beginTransaction() 메소드를 호출해야 한다.
private FragmentManager fm = getSupportFragmentManager();
위와 같이 FragmentManager 객체를 호출하고,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setcontentView(R.layout.activity_main);
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_01, new Fragment01());
ft.commit();
}
private void setFragment(int fragmentName) {
// ...
ft.replace(R.id.fragment_02, new Fragment02());
ft.commit();
// ...
}
- 위와 같이 하나의 트랜잭션에서 또 프래그먼트 전환 처리를 하면 다음과 같은 에러가 난다.
commit already called
그러므로 다른 프래그먼트를 호출해야 한다면 다음과 같이 트랜잭션 객체를 새롭게 생성해야 한다.
private void setFragment(int fragmentName) {
// ...
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_02, new Fragment02());
ft.commit();
// ...
}
- 즉, 프래그먼트의 commit() 메소드는 호출이 필요할 때 마다 FragmentTransaction을 생성하면 된다.
이상 끗~!