관리 메뉴

java,javascript,android,php,sql,공부용,메모용

안드로이드앱 프래그먼트 수명주기 상태메서드 onAttach() / Android Studio / 안드로이드 앱만들기 27 본문

모바일/안드로이드앱

안드로이드앱 프래그먼트 수명주기 상태메서드 onAttach() / Android Studio / 안드로이드 앱만들기 27

yy_dd2 2021. 3. 20. 19:27
반응형

프래그먼트 수명주기

프래그먼트도 액티비티를 본떠 만들었기 때문에 액티비티처럼 독립적으로 동작하게 만들어주는 수명주기가 있다.

액티비티에 종속되어 있는 프래그먼트는 onResume() onPause() 같은 메서드 외에 세분화된 상태 메서드가 있다.

 

프래그먼트가 화면에 보이기 전까지 호출될 수 있는 상태 메서드 (수명주기 메서드)

메서드 설명
 onAttach(Activity)  프래그먼트가 액티비티와 연결될 때 호출됨
 onCreate(Budle)  프래그먼트가 초기화될 때 호출됨.
 (new 연산자를 이용해 새로운 프래그먼트 객체를 만드는 시점이 아님)
 onCreateViuew(LayoutInflator, ViewGroup, Bundle)  프래그먼트와 관련되는 뷰 계층을 만들어서 리턴함.
 onActivityCreated(Bundle)  프래그먼트와 연결된 액티비티가 onCreate() 메서드로 작업을 완료하면 호출됨
 onStart()  프래그먼트와 연결된 액티비티가 onStart()되어 사용자에게 프래그먼트가 보일 때 호출됨
 onResume()  프래그먼트와 연결된 액티비티가 onResume()되어 사용자와 상호작용 할 수 있을때 호출됨

 

액티비티가 메모리에 처음 만들어질때 onCreate()메서드가 생기듯

프래그먼트가 초기화 될때 onCreate()가 호출된다.

 

프래그먼트가 화면에서 보이지 않게 되면 호출되는 상태 메서드 (수명주기 메서드)

메서드 설명
 onPause()  프래그먼트와 연결된 액티비티가
 onPause()되어 사용자와 상호작용을 중지할때 호출
 onStop()  프래그먼트와 연결된 액티비티가 onStop()되어
 화면에 더 이상 보이지 않을 때, 프래그먼트가 중지되었을때 호출
 onDestoryView()  프래그먼트와 관련된 뷰 리소스를 해제할 수 있도록 호출
 onDestroy()  프래그먼트의 상태를 마지막으로 정리하게 호출
 onDetach()  프래그먼트가 액티비티와 연결을 끊기 바로 전에 호출.

 

**주의할점 / 기억할점

- 프래그먼트는 액티비티 안에 추가되어 사용되면서 동시에 액티비티에 종속되어있다 그래서 프래그먼트와 액티비티가 연결되어야 초기화가 가능하다.

- 프래그먼트 수명주기 메서드는 프래그먼트 객체가 new 연산자로 만들어졌어도 액티비티 위에 올리기 전까지 프래그먼트로 동작하지 않는다는 점

MyFragment fragment = new MyFragment();

-> 프래그먼트 객체는 만들어졌다 / 프래그먼트 동작 안함


getSupportFragmentManager().beginTransaction().add(fragment).commit();

-> 액티비티 추가되고 프래그먼트로 동작됨 commit

 


프래그먼트로 화면 만들기

 

1. SampleFragment2

- 패키지이름 변경 (난 안했음)
- 책에서 제공한다는 이미지 복사해서 /app/res/drawable 폴더 안에 복사하라고 함 (아무 이미지나 3개 복사함)

2. /app/res/layout 폴더에 activity_main.xml 복사해서 fragment_list.xml으로 만든다.

버튼3개추가 최상위레이아웃 리니어레이아웃 vertical

3. MainActivity.java 복사해서 ListFragment.java 만들고 인플레이션한다

4. activity_main.xml 복사해서 fragment_viewer.xml 만듬

이미지 1개를 추가하고 최상위레이아웃 리니어에이아웃 vertical

5. 코드 전문

 

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">

    <fragment
        android:id="@+id/listFragment"
        android:name="com.togapp.samplefragment2.ListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/viewFragment"
        android:name="com.togapp.samplefragment2.ViewerFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

MainActivity.java

더보기
package com.togapp.samplefragment2;

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

import android.os.Bundle;

public class MainActivity extends AppCompatActivity
                            implements ListFragment.ImageSelectionCallback {
    ListFragment listFragment;
    ViewerFragment viewerFragment;

    int[] images = {R.drawable.test_moon1, R.drawable.test_moon2, R.drawable.wheat_1};

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

        FragmentManager manager = getSupportFragmentManager();
        listFragment = (ListFragment) manager.findFragmentById(R.id.listFragment);
        viewerFragment = (ViewerFragment) manager.findFragmentById(R.id.viewFragment);
    }

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

 

fragment_list.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" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="첫 번째 이미지" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="두 번째 이미지" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="세 번째 이미지" />
</LinearLayout>

ListFragment.java

더보기
package com.togapp.samplefragment2;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

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

public class ListFragment extends Fragment {

    // 각각의 버튼을 눌렀을 때 호출될 메서드
    public interface ImageSelectionCallback{
        void onImageSelected(int position);
    }

    public ImageSelectionCallback callback;

    // onAttach() 메서드는 프래그먼트가 액티비티 위에 올라가는 시점에 호출됨됨
    // ctrl + o onAttach 호출
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof ImageSelectionCallback) {
            callback = (ImageSelectionCallback) context;
        }
    }

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

        Button button = rootView.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.onImageSelected(0);
                }
            }
        });

        Button button2 = rootView.findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.onImageSelected(1);
                }
            }
        });

        Button button3 = rootView.findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.onImageSelected(2);
                }
            }
        });

        return rootView;
    }
}

fragment_viewer.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">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/test_moon1" />
</LinearLayout>

ViewerFragment.java

더보기
package com.togapp.samplefragment2;

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

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

public class ViewerFragment extends Fragment {
    ImageView imageView;

    @NonNull
    @Override
    public View onCreateView(LayoutInflater inflater, @NonNull ViewGroup container, @NonNull Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_viewer,container, false);

        imageView = rootView.findViewById(R.id.imageView);
        return rootView;
    }

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

 

 

1. ListFragment.java 에 만들어진 interface ImageSelectionCallback 를

MainActivity.java 에 implements ListFragment.ImageSelectionCallback

 

ListFragment.java를 보면


// 각각의 버튼을 눌렀을 때 호출될 메서드
public interface ImageSelectionCallback{
void onImageSelected(int position);
}

public ImageSelectionCallback callback;

    // onAttach() 메서드는 프래그먼트가 액티비티 위에 올라가는 시점에 호출됨됨
    // ctrl + o onAttach 호출
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof ImageSelectionCallback) {
            callback = (ImageSelectionCallback) context;
        }
    }
    
    

버튼을 누르면

                if (callback != null) {
                    callback.onImageSelected(0);
                }

각각 버튼마다 callbackonImageSelected(0)을 호출한다.

 

각각 버튼을 누를때마다 호출될 메서드는

// 각각의 버튼을 눌렀을 때 호출될 메서드
public interface ImageSelectionCallback{
void onImageSelected(int position);
}

이부분이고

 

MainActivity.java 안에

    int[] images = {R.drawable.test_moon1, R.drawable.test_moon2, R.drawable.wheat_1};

이미지를 이렇게 저장시키고

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

메서드를 만들어서

각각의 버튼을 누르면

  setImage(images[0]); 이런식으로 호출된다

ImageSelectionCallback안에 있던 onImageSelected() 이 호출된다 버튼을 누르면 callback.onImageSelected(0); 을 저장했으니 0이 호출되고 images 배열안에 [0]이 호출된다

 

 

실행화면

 


UI를 만들때 프래그먼트는 필수로 사용되니 잘 알아두는게 좋을것

 

github.com/young-0112/SampleFragment2

 

young-0112/SampleFragment2

프래그먼트 수명주기, 상태메서드 onAttach(). Contribute to young-0112/SampleFragment2 development by creating an account on GitHub.

github.com

 

반응형
Comments