power-girl0-0

프래그먼트를 이용하여 앨범만들기 본문

언어/Android

프래그먼트를 이용하여 앨범만들기

power-girl0-0 2020. 11. 25. 16:09
728x90

 

안녕하세요!! 프래그먼트를 이용하여 앨범을 만들어 보겠습니다!!

이번 컨셉은 원하는 요소의 체크박스를 눌렀을 때 사진이 출력되는 앨범을 만들 예정입니다!!

요즘 유행하는 드라마 '스타트업 등장인물'을 주제로 만들었어요!! 

 


Fragment(프래그먼트)란?

하나의 액티비티가 여러개의 화면을 가지도록 만든 개념이다. 전에는 하나의 Activity를 SubActivity 단위로 사용하기 위해 ActivityGroup으로 여러 Activity를 하나로 묶어서 사용하였다. 해당 방법은 장점보다 유지관리 및 Lifecycle관리가 힘들기 때문에 나온 것이 프래그먼트이다. 즉, 프래그먼트는 액티비티 내에서 여러 개의 프래그먼트를 조합하여 액티비티가 출력하는 한 화면의 UI를 표현할 수 있으며 하나의 프래그먼트를 다른 액티비티에서 재사용할 수 있는 것이다.

Fragment의 생명주기

해당 Frangment는 여러 장점을 가지지만 반드시 하나의 액티비티 안에 소속되어야하고, 독립적인 생명주기를 가지기 때문에 프래그먼트의 동작원리를 알아야합니다.

출처 : tedrepository.tistory.com/5


화면구성

먼저, 원하는 요소를 선택할 수 있는 프래그먼트를 생성하였다. -> ChooseFragment

xml 소스는 다음과 같다.

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="15dp"
        android:text="스타트업 등장인물"
        android:textSize="28sp"
        android:textStyle="bold" />

    <View
        android:background="#000000"
        android:layout_width="match_parent"
        android:layout_height="10px"
        android:layout_marginBottom="15dp"
        />
    <RadioGroup
        android:id="@+id/rdGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/rdBtn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="모두보기"
            android:textSize="23sp" />

        <RadioButton
            android:id="@+id/rdBtn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="서달미"
            android:textSize="23sp" />

        <RadioButton
            android:id="@+id/rdBtn3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="남도산"
            android:textSize="23sp" />

        <RadioButton
            android:id="@+id/rdBtn4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="한지평"
            android:layout_marginBottom="15dp"
            android:textSize="23sp" />

    </RadioGroup>
    <View
        android:background="#000000"
        android:layout_width="match_parent"
        android:layout_height="10px"
        android:layout_marginBottom="5dp"
        />

    <Button
        android:id="@+id/btnOk"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:background="#37CDDC39"
        android:text="OK"
        android:textColor="#F44336"
        android:textSize="25sp"
        android:textStyle="bold"
        android:layout_marginBottom="5dp"
        />


</LinearLayout>

 

두번째, 원하는 요소에 맞는 사진을 출력하기 위해 프래그먼트를 생성하였다. -> ViewFragment

아래는 해당 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="wrap_content"
    android:layout_height="match_parent"
    android:background="#ECDFE4"
    android:orientation="vertical"
    tools:context=".ViewFragment">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/main" />
</LinearLayout>

 

마지막으로 Activity에서 두개의 프래그먼트를 불러왔다.

해당 소스는 MainActivity의 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">

    <fragment
        android:id="@+id/chooseFragment"
        android:name="org.techtown.a2a_2019202123.ChooseFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/viewFragment"
        android:name="org.techtown.a2a_2019202123.ViewFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

기능구성

이제 자바소스를 생성하여 해당 기능들이 실행되도록 하였다.

 

먼저, MainActivity.java소스이다.

package org.techtown.a2a_2019202123;

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

import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements ImageSelectionCallback{
    ChooseFragment chooseFragment;
    ViewFragment viewFragment;
    int[] images={R.drawable.main, R.drawable.su, R.drawable.nam, R.drawable.han};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager manager = getSupportFragmentManager();
        chooseFragment = (ChooseFragment) manager.findFragmentById(R.id.chooseFragment);
        viewFragment = (ViewFragment) manager.findFragmentById(R.id.viewFragment);
    }

    @Override
    public void onImageSection(int position) {
        viewFragment.setImage(images[position]);
    }

}

 

여기서!!

ImageSelectionCallback.java의 interface를 설정해서 원하는 요소에 맞는 이미지 출력값을 받아오도록 하였다.

아래는 해당 소스이다.

package org.techtown.a2a_2019202123;

public interface ImageSelectionCallback {
    public void onImageSection(int position);
}

 

 

두번째는 원하는 요소 체크에 대한 ChooseFragment.java소스이다.

package org.techtown.a2a_2019202123;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class ChooseFragment extends Fragment {
    ImageSelectionCallback callback;
    RadioGroup rdGroup;
   RadioButton rdBtn1, rdBtn2, rdBtn3, rdBtn4;

    Button btnOk;
    ViewGroup rootView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(context instanceof ImageSelectionCallback){
            callback = (ImageSelectionCallback)context;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = (ViewGroup)inflater.inflate(R.layout.fragment_choose,container,false);
        rdGroup = rootView.findViewById(R.id.rdGroup);
        rdBtn1 = rootView.findViewById(R.id.rdBtn1);
        rdBtn2 = rootView.findViewById(R.id.rdBtn2);
        rdBtn3 = rootView.findViewById(R.id.rdBtn3);
        rdBtn4 = rootView.findViewById(R.id.rdBtn4);
        btnOk = rootView.findViewById(R.id.btnOk);



        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(rdBtn1.isChecked()) {
                    callback.onImageSection(0);
                }
                else if(rdBtn2.isChecked()) {
                    callback.onImageSection(1);
                }
                else if(rdBtn3.isChecked()) {
                    callback.onImageSection(2);
                }
                else{
                    callback.onImageSection(3);
                }
            }
        });

        return rootView;
    }
}

 

마지막으로, 이미지 출력 화면에 대한 ViewFragment.java소스이다.

package org.techtown.a2a_2019202123;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class ViewFragment extends Fragment {
    ImageView img;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_view, container, false);
        img = rootView.findViewById(R.id.img);

        return rootView;
    }

    public void setImage(int resId) {
        img.setImageResource(resId);
    }
}

 

 

마지막으로는 실행된 화면이다!!

728x90
Comments