안드로이드 버튼클릭으로 프래그먼트 (Fragment) 화면 변경하기

 계발에서 개발까지 

 

 

안드로이드 버튼클릭으로 프래그먼트 화면 변경하기.

Fragment는 Activity와 함께 UI를 구성하는 요소로 자주 사용합니다. Fragment는 항상 Activity위에 호스팅이 되어야 하기 때문에 이 점 주의하시면서 UI를 구성하시면 되겠습니다. 오늘은 간단한 방법으로  Fragment의 화면을 버튼으로 제어하는 예제를 알아보겠습니다. 일단 MainActivity위에 Fragment가 올라가야 하기 때문에 밑에 코드처럼 구성하시면 되겠습니다.

 

MainActivity.java

MainActivity에 Fragment를 사용해야하기 때문에 프래그먼트 사용설정을 해줍니다. Fragment 화면을 2개를 준비해주시고 버튼클릭으로 변경하겠습니다. 화면을 더 추가하고싶으시면 화면을 더 준비해주시면 됩니다.

public class MainActivity extends AppCompatActivity {
    private final int Fragment_1 = 1;
    private final int Fragment_2 = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                FragmentView(Fragment_1);

            }
        });

        findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentView(Fragment_2);


            }
        });
        FragmentView(Fragment_1);
    }

    private void FragmentView(int fragment){

     //FragmentTransactiom를 이용해 프래그먼트를 사용합니다.
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        switch (fragment){
            case 1:
	// 첫번 째 프래그먼트 호출
                Fragment1 fragment1 = new Fragment1();
                transaction.replace(R.id.fragment_container, fragment1);
                transaction.commit();
                break;

            case 2:
	// 두번 째 프래그먼트 호출
                Fragment2 fragment2 = new Fragment2();
                transaction.replace(R.id.fragment_container, fragment2);
                transaction.commit();
                break;
        }

    }


}

 

Fragment1.java

public class Fragment1 extends Fragment {


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.fragment1, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


    }
}
 

Fragment2.java

public class Fragment2 extends Fragment {


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.fragment2, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


    }
}

이렇게하면 화면준비는 끝났으니 이제 레이아웃을 설정해줍니다.

 

activity_main.xml

activity_main에는 버튼 2개와 프래그먼트 사용을 위한 FragmentLayout를 만들어줍니다. FragmentLayout의 공간이 화면변경합니다.

<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
tools:context=".MainActivity">

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


    <Button
        android:id="@+id/btn1"
        android:text="프래그먼트 1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:id="@+id/btn2"
        android:text="프래그먼트 2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>


<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"/>

</LinearLayout>
​

 

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical"
    android:background="#123"
    tools:context=".MainActivity">



</LinearLayout>

 

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical"
    android:background="#321"
    tools:context=".MainActivity">



</LinearLayout>

레이아웃까지 생성해주고 적용시켜주면 밑에 화면처럼 구성이 될껍니다 이제 디바이스를 실행시켜 버튼을 클릭해서 Fragment화면이 변경되는지 테스트를 해주면 됩니다. 수고하셨습니다.

 
 

 

수고하셨습니다 ★

더 많은 정보

 https://deumdroid.tistory.com/ 

 

댓글

Designed by JB FACTORY