2020. 7. 12. 16:15ㆍ공부 정리/안드로이드
getSupportFragmentManager()는 안드로이드 이전 버전들에서도 프래그먼트를 사용할 수 있도록 만든 appcompat_v7 라이브러리 프로젝트에서 지원하는 기능입니다. 따라서 getFragmentManager()로 쓰지 말고 getSupportFragmentManager()로 쓰는 것이 좋습니다.
FragmentManager 클래스는 런타임 시 활동에 프래그먼트를 추가, 삭제 및 교체할 수 있는 메서드를 제공합니다.
프래그먼트 추가 또는 삭제와 같은 트랜잭션을 실행하려면 FragmentManager를 사용하여 FragmentTransaction을 생성해야 하며 이 클래스에서는 다른 프래그먼트 트랜잭션을 추가, 삭제, 교체 및 실행하는 API를 제공합니다.
프래그먼트를 사용중에 삭제와 교체를 허용한다면, onCreate() 메서드를 실행하는 동안 초기 프래그먼트를 추가해야 합니다.
동적으로 프래그먼트를 추가할 때 유념해야 할 중요한 규칙은 프래그먼트를 삽입할 수 있는 View 컨테이너를 레이아웃에서 포함해야 하는 것입니다.
지원 라이브러리 API를 통해 getSupportFragmentManager()를 호출하여 FragmentManager를 가져옵니다. 그런 다음, beginTransaction()을 호출하여 FragmentTransaction을 생성하고 add()를 호출하여 프래그먼트를 추가합니다.
동일한 FragmentTransaction을 사용하여 여러 프래그먼트 트랜잭션을 실행할 수 있습니다. 변경할 준비가 되면 commit()을 호출해야 합니다.
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
HeadlinesFragment firstFragment = new HeadlinesFragment();
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}
출처: https://developer.android.com/training/basics/fragments/fragment-ui?hl=ko#java
'공부 정리 > 안드로이드' 카테고리의 다른 글
안드로이드 fragment replace (0) | 2020.07.12 |
---|---|
안드로이드 프래그먼트 - 2 (0) | 2020.07.12 |
안드로이드 프래그먼트 - 1 (0) | 2020.07.12 |
안드로이드 인터넷 연결상태 확인 getNetworkCapabilities (0) | 2020.07.08 |
안드로이드 네트워크 보안 구성 - http연결 (0) | 2020.07.08 |