안드로이드 fragment replace
2020. 7. 12. 17:30ㆍ공부 정리/안드로이드
프래그먼트에서 프래그먼트로 화면을 전환할 때 FragmentManager를 통해서 replace()를 하면 되지만 이 작업이 반복될 경우 코드가 길어지고 난잡해질 수 있습니다. 이를 해결하기 위해서 프래그먼트를 씌운 액티비티에서 메소드화를 하면 사용하기 편합니다.
<프래그먼트를 싼 액티비티>
public void replaceFragment(Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(null);
ft.commit();
}
<프래그먼트>
public class ExFragment extends Fragment {
Button btn;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.Ex_fragment, container, false);
btn = (Button) rootView.findViewById(R.id.fragment_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//예제 소스에서 fragment를 싸고 있는 액티비티가 mainactivity
((MainActivity) getActivity()).replaceFragment(화면 전환 할 프래그먼트);
}
});
return rootView;
}
'공부 정리 > 안드로이드' 카테고리의 다른 글
안드로이드 FragmentManager (0) | 2020.07.12 |
---|---|
안드로이드 프래그먼트 - 2 (0) | 2020.07.12 |
안드로이드 프래그먼트 - 1 (0) | 2020.07.12 |
안드로이드 인터넷 연결상태 확인 getNetworkCapabilities (0) | 2020.07.08 |
안드로이드 네트워크 보안 구성 - http연결 (0) | 2020.07.08 |