본문 바로가기

major/Android

[Android] Fragment 구현

한 화면 안에 여러 개의 화면 요소를 나타내기 위해서 Fragment를 사용합니다.

아래와 같이 버튼을 클릭했을 때, 각 Fragment를 보여지도록 만드는 예제 코드를 정리했습니다.

Fragment 화면

먼저 Frag1.java, frag1.xml, Frag2.java, frag2.xml을 생성하고 아래의 코드를 복붙합니다.

// Frag1.java
public class Frag1 extends Fragment {

    View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState){
        view = inflater.inflate(R.layout.frag1,container,false);

        return view;
    }
}
// frag1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff0000">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fragment1입니다."/>

</LinearLayout>
// Frag2.java
public class Frag2 extends Fragment {

    View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState){
        view = inflater.inflate(R.layout.frag2,container,false);

        return view;
    }
}
// frag2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fragment2입니다."/>

</LinearLayout>

MainActivity.java와 activity_main.xml 코드를 수정합니다.

// MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView txt;
    Button btn1, btn2;
    Frag1 frag1;
    Frag2 frag2;
    FragmentManager fm;
    FragmentTransaction tran;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView)findViewById(R.id.main_txt);
        btn1 = (Button)findViewById(R.id.btn1);
        btn2 = (Button)findViewById(R.id.btn2);

        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);

        frag1 = new Frag1();
        frag2 = new Frag2();

        setFragment(0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                setFragment(0);
                break;
            case R.id.btn2:
                setFragment(1);
                break;
        }
    }

    public void setFragment(int n) {
        fm = getSupportFragmentManager();
        tran = fm.beginTransaction();
        switch (n) {
            case 0:
                tran.replace(R.id.fragment, frag1);
                tran.commit();
                break;
            case 1:
                tran.replace(R.id.fragment, frag2);
                tran.commit();
                break;
        }
    }
}
// activity_main.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/main_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="frag1"/>

        <Button
            android:id="@+id/btn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="frag2"/>

    </LinearLayout>

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

</LinearLayout>

잘못된 내용이 있다면 언제든지 댓글이나 메일로 알려주시면 감사하겠습니다.

이 포스팅이 도움이 되었다면 공감 부탁드립니다.

궁금한 점은 언제든지 댓글 남겨주시면 답변해드리겠습니다:D