Before 2022/Android

Fragment 다루기

Eljoe 2019. 1. 15. 17:31
public class TestActivity extends FragmentActivity {
    //프레그먼트 매니저
    private FragmentManager fragmentManager;

    private VerifyingFragment verifyingFragment;
    private WaitingFragment waitingFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        
        //버터나이프 라이브러리
        ButterKnife.bind(this);

        //프레그먼트 초기화
        verifyingFragment = new VerifyingFragment();
        waitingFragment = new WaitingFragment();

        //프레그먼트 매니저 초기화
        fragmentManager = getSupportFragmentManager();
        
        //프레그먼트에 값 전달할 때
        Bundle bundle = new Bundle(1);
        bundle.putString("value", "test");
        verifyingFragment.setArguments(bundle);
		
        //액티비티에 해당 프레그먼트가 붙어있는가?
        if(!verifyingFragment.isAdded())fragmentManager.beginTransaction().add(R.id.fl_certification, verifyingFragment).commit();
    }

    private void changeFragmentAfterRemove(){
        //해당 프레그먼트를 재사용할 필요가 없을 때 remove
        fragmentManager.beginTransaction().remove(verifyingFragment).commit();
        fragmentManager.beginTransaction().replace(R.id.fl_certification, waitingFragment).commit();
    }
	
    private void changeFragmentAfterStack(){
        //해당 프레그먼트를 재사용할(Back 버튼을 누른 경우) 필요가 있을 때 addToBackStack
        fragmentManager.beginTransaction().replace(R.id.fl_certification, waitingFragment);
        fragmentManager.beginTransaction().addToBackStack(null);
        fragmentManager.beginTransaction().commit();
    }
}