안드로이드 Fragment 초보자를 위하여 간단하게 소스만을 정리 해볼까 합니다

fragment 생명주기등 여러가지 설명을 해야 하지만 fragment에 대한 내용은

이미 많은 분들이 포스팅해서 저는 소스만을 소개 해드리겠습니다 ^^


일단 fragment 를 사용하기위하여 레이아웃안에 FrameLayout을 추가 해줘야 합니다.


Fragment 를 사용할 xml 안에 아래 소스를 입력해 주시면 됩니다.

FrameLaouy 안에 Fragment 화면이 보여지게 됩니다.


<FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>


이제 fragment 를 사용해보겠습니다

Fragment를 생성하고 위에서 추가한 framelayout에 화면을 보여주는 소스입니다.


FragTsaction 는 fragment를 관리하기 위하여 생성합니다.


FragmentTransaction FragTsaction = getSupportFragmentManager().beginTransaction();


// 아래와 같이 생성하시거나 excalss.instanc(); 식으로 생성 하셔도 되며.

// intance는 따로 static으로 정의를 한 것입니다.
FragTsaction.replace(R.id.main_frame, new excalss()); 


// fragment 보여지거나 사라질때 애니메이션 처리 입니다.
FragTsaction.setCustomAnimations

(R.anim.layout_leftin, R.anim.layout_leftout)


//replace(R.id.newmain_frame, targetFragment, "newmain_fragment")

//위에 repace 방법과 동일하지만 파라미터 하나가 더있습니다.

//마지막 파라미터 "newmain_fragment" 값은

//이름을 정해준다고 생각 하시면 됩니다. 

//추가해둔 fragment를 다시 불러 올때사용 됩니다


FragTsaction.commit();  // 마지막으로 commint을 해주면 동작을 하게됩니다.



마지막으로 추가한 fragment불러와서 화면에서 사라지게하거나 삭제하는 소스입니다.


Fragment 페이지 삭제 방법 2가지가 이습니다.


1번 framelayout id 값으로 추가된 fragment를 불러와서 remove 시켜주는 방법입니다.
Fragment mFragment = getSupportFragmentManager().findFragmentById(R.id.main_frame);
FragTsaction.remove(mFragment);


2번 위에서 설명 했던 지어준 이름을 가지고 remove 시켜주는 방법입니다.
Fragment mFragment = getSupportFragmentManager().findFragmentByTag("newmain_fragment")
FragTsaction.remove(mFragment);
 


fragment에대하여 더욱 자세하게 알고 사용하면 좋지만

여기저기 블로그를 보시다가 정리가 안되시는 분들은 위에 소스를 사용해보시고

이론을 다시한번 보시면 더욱 쉽게 이해가 가실거라 생각됩니다.

또한 개발도 위에소스만으로도 충분하게 개발은 가능합니다 그래도 이론적으로 알고

개발하시는게 더욱 좋을거라 생각 됩니다. ^^


추가로 위에서 사용된 애니메이션과 intance 를 보여드리고 마무리 하겠습니다.


fragment class 에서 생성하시면 됩니다.

public static exclass Instance(int i){
        exclass fragment = new exclass();
        Bundle args = new Bundle();
        args.putInt("Num", i);
        fragment.setArguments(args);
        return fragment;
    }

애니메이션1 입니다. R.anim.layout_leftin
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromXDelta="100%p"
        android:toXDelta="0" />

</set>

애니메이션2 R.anim.layout_leftout
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromXDelta="0"
        android:toXDelta="-100%p" />

</set>

+ Recent posts