본문 바로가기
코리아 IT아카데미/android

8일차 | 디자인패턴, 프래그먼트 만들어 보기

by Sharon kim 2022. 2. 28.

https://developer.android.com/guide/components/fragments?hl=ko

 

프래그먼트  |  Android 개발자  |  Android Developers

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section

developer.android.com

생명주기

- xml 에서 생성하는 방법

- 자바코드로 생성하는 방법 (프래그먼트 매니저, 트랜잭션 처리)

- 자바코드로 제거하는 방법

디자인 패턴

adapter>

AirConditioner.java

package com.example.myfragment.adapter;

public class AirConditioner implements Electronic220v {

    @Override
    public void connect() {
        System.out.println("에어콘 연결 됨 ~ 220v On");
    }
}

 

Cleaner.java

package com.example.myfragment.adapter;

public class Cleaner implements Electronic110v {
    @Override
    public void connect() {
        System.out.println("청소기 연결 110v On ~");
    }
}

 

HairDryer.java

package com.example.myfragment.adapter;

public class HairDryer implements Electronic110v {

    @Override
    public void connect() {
        System.out.println("헤어 드라이기 연결 110v On");
    }
}

 

Electronic110v.interface

package com.example.myfragment.adapter;

public interface Electronic110v {
    void connect();
}

 

Electronic220v.interface

package com.example.myfragment.adapter;

public interface Electronic220v {
    void connect();
}

 

ElectronicAdapter.java

package com.example.myfragment.adapter;

public class ElectronicAdapter implements Electronic220v {

    Electronic110v electronic110v;

    public ElectronicAdapter(Electronic110v electronic110v) {
        this.electronic110v = electronic110v;
    }

    @Override
    public void connect() {
        electronic110v.connect();
    }
}

MyHouse.java

package com.example.myfragment.adapter;

public class MyHouse {

    public static void main(String[] args) {

        AirConditioner airConditioner = new AirConditioner();
        connect(airConditioner);

        HairDryer hairDryer = new HairDryer();
        ElectronicAdapter electronicAdapter1 = new ElectronicAdapter(hairDryer);
        connect(electronicAdapter1);

        Cleaner cleaner = new Cleaner();
        ElectronicAdapter electronicAdapter2 = new ElectronicAdapter(cleaner);
        connect(electronicAdapter2);
        //connect(cleaner);
//        connect(hairDryer);
    }

    // 전기 콘센트
    public static void connect(Electronic220v electronic220v) {
        electronic220v.connect();
    }
}

 


 

builder>

Student.java

package com.example.myfragment.builder;

public class Student {

    private String name;
    private int grade;

    private Student() {
    }

    public static class MyBuilder {

        private String name;
        private int grade;

        public MyBuilder setName(String name) {
            this.name = name;
            return this;
        }

        public MyBuilder setGrade(int grade) {
            this.grade = grade;
            return this;
        }

        // 핵심
        public Student build() {
            Student student = new Student();
            student.name = this.name;
            student.grade = this.grade;
            return student;
        }
    } // 내부 정적 클래스

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", grade=" + grade +
                '}';
    }
}

MainTest.java

package com.example.myfragment.builder;

public class MainTest {

    public static void main(String[] args) {
        Student student = new Student.MyBuilder()
                .setName("홍길동")
                .setGrade(3)
                .build();

        Student student1 = new Student.MyBuilder().setName("이순신").setGrade(1).build();

        System.out.println(student.toString());
        System.out.println(student1.toString());
    }
}

 



singleton>

AClass.java

package com.example.myfragment.singleton;

public class AClass {

    private MyPrinter myPrinter;

    public AClass() {
        myPrinter = MyPrinter.getInstance();
    }

    public MyPrinter getMyPrinter() {
        return this.myPrinter;
    }

}

 

BClass.java

package com.example.myfragment.singleton;

public class BClass {

    private MyPrinter myPrinter;

    public BClass() {
        myPrinter = MyPrinter.getInstance();
    }

    public MyPrinter getMyPrinter() {
        return this.myPrinter;
    }
}

 

MyPrinter.java

package com.example.myfragment.singleton;

public class MyPrinter {

    private static MyPrinter myPrinter;

    // 1. private // new MyPrinter() <-- X (호출 안됨)
    private MyPrinter() {

    }

    public static MyPrinter getInstance() {
        if(myPrinter == null) {
            myPrinter = new MyPrinter();
        }
        return myPrinter;
    }
}

MainTest.java

package com.example.myfragment.singleton;

public class MainTest {

    public static void main(String[] args) {

        AClass aClass = new AClass();
        BClass bClass = new BClass();

        System.out.println("인스턴스비교");

        MyPrinter myPrinter1 = aClass.getMyPrinter();
        MyPrinter myPrinter2 = bClass.getMyPrinter();

        System.out.println(myPrinter1.equals(myPrinter2));

    }
}

 



activity_main.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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Main Activity"
        android:textSize="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!--
        반드시 ID 값을 지정해 주어야 한다.
        name 값도 지정해주어야 한다.
    -->
<!--    <fragment-->
<!--        android:id="@+id/fragmentOne"-->
<!--        android:name="com.example.myfragment.OneFragment"-->
<!--        android:layout_width="match_parent"-->
<!--        android:layout_height="200dp" />-->

    <Button
        android:id="@+id/createFragmentButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_create" />

    <Button
        android:id="@+id/removeFragmentButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_remove" />

    <LinearLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#46A5CF"
        android:orientation="vertical" />


</LinearLayout>


fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple_200"
    tools:context=".OneFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

fragment_two.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TwoFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>


MainActivity.java

package com.example.myfragment;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button createFragmentButton;
    Button removeFragmentButton;
    OneFragment oneFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d("TAG", "Activity : onCreate ");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createFragmentButton = findViewById(R.id.createFragmentButton);
        removeFragmentButton = findViewById(R.id.removeFragmentButton);
        oneFragment = new OneFragment();

        // 데이터를 전달하는 방법
        Bundle bundle = new Bundle();
        bundle.putString("param1", "안녕하세요");
        oneFragment.setArguments(bundle);


        FragmentManager fragmentManager = getSupportFragmentManager();
//        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        createFragmentButton.setOnClickListener(v -> {
            // 자바 코드로 프래그먼트를 생성하는 방법
            //oneFragment = new OneFragment();
            // 1. FragmentManager ( 프래그먼트 트랜잭션을 객체를 가져올 수 있다)
            // 2. FragmentTransaction -> 작업의 단위( 시작과 끝이 있다)
            //FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            // replace / add
            fragmentTransaction.replace(R.id.fragmentContainer, oneFragment);
            fragmentTransaction.commit();
            // commit() : 시간될 때 완료해
            // commitNow()  : 지금 당장해 !!!
            // commitAllowingStateLoss() <--- 위험 (커밋이 없어질 수 있다)
        });

        removeFragmentButton.setOnClickListener(v -> {
            // 자바코드로 프래그먼트 제거 하기
            // remove, detach
            // remove : 인스턴스를 다시 연결할 수 없다. : 프래그먼트 트랜잭션에 다시 추가해야 한다.
//            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.remove(oneFragment);
            fragmentTransaction.commit();
        });

    }

    @Override
    protected void onStart() {
        Log.d("TAG", "Activity : onStart ");
        super.onStart();
    }

    @Override
    protected void onResume() {
        Log.d("TAG", "Activity : onResume ");
        super.onResume();
    }

    @Override
    protected void onPause() {
        Log.d("TAG", "Activity : onPause ");
        super.onPause();
    }

    @Override
    protected void onStop() {
        Log.d("TAG", "Activity : onStop ");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d("TAG", "Activity : onDestroy ");
        super.onDestroy();
    }

}


OneFragment.java

package com.example.myfragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class OneFragment extends Fragment {

    @Override
    public void onAttach(@NonNull Context context) {
        Log.d("TAG" , "Fragment : onAttach ~" );
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.d("TAG" , "Fragment : onCreate ~" );
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d("TAG" , "Fragment : onCreateView ~" );

        View view = inflater.inflate(R.layout.fragment_one, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d("TAG" , "Fragment : onViewCreated ~" );

        if(getArguments() != null) {
            String data = getArguments().getString("param1", "");
            Log.d("TAG", "data :" + data);

            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle("알림")
                    .setMessage("넘겨 받은 데이터 " + data)
                    .setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 아무 동작 안함
                        }
                    }).setNegativeButton("취소", (dialog, which) -> {
                        // 아무 동작 안함
            });

            builder.show();
        }

        super.onViewCreated(view, savedInstanceState);
    }


    @Override
    public void onStart() {
        Log.d("TAG" , "Fragment : onStart ~" );
        super.onStart();
    }

    @Override
    public void onResume() {
        Log.d("TAG" , "Fragment : onResume ~" );
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.d("TAG" , "Fragment : onPause ~" );
        super.onPause();
    }

    @Override
    public void onDestroyView() {

        Log.d("TAG" , "Fragment : onDestroyView ~" );
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Log.d("TAG" , "Fragment : onDestroy ~" );
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        Log.d("TAG" , "Fragment : onDetach ~" );
        super.onDetach();
    }

}


TwoFragment.java

package com.example.myfragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TwoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TwoFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public TwoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TwoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TwoFragment newInstance(String param1, String param2) {
        TwoFragment fragment = new TwoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_two, container, false);
    }
}