[Android] Fragment

Taewoo Kim·2022년 12월 15일
0

[Android]

목록 보기
6/8

이 내용은 joyce의 안드로이드 앱 프로그래밍의 내용과 Android Developer Docs를 참고했습니다.

Fragment란?

FragmentActivity 내의 어떤 동작 또는 사용자 인터페이스의 일부를 나타낸다. 여러 개의 Fragment를 하나의 Activity에 결합하여 창이 여러 개인 UI를 빌드할 수 있으며, 하나의 Fragment를 여러 Acticity에서 재사용할 수 있다. Fragment는 모듈식 섹션이라고 생각하면 된다.

그렇기 때문에 자체적인 Life Cycle을 가지고 자체 입력 이벤트를 수신하며, 액티비티 실행 중에 추가 및 삭제가 가능해진다.

  • 항상 Activity 내에서 호스팅되어야 하며 해당 Fragment의 Life Cycle은 Host Activity의 수명 주기에 직접적으로 영향을 받는다.(Fragment의 Life Cycle은 따로 존재)
  • Activity가 실행 중인 동안 각각의 Fragment를 추가 또는 제거하는 개별적 조작이 가능

Fragment Life Cycle

onAttach()

Fragment가 Host Activity에 attacgh되고 나서 호출되는 함수이다.

onCreate()

Fragment가 생성될 때 시스템에서 이것을 호출
구현 내에서 Fragment의 기본 구성 요소 중 Fragment가 일시정지 되거나 중단되었다가 재개되었을 때 유지하고자 하는 것을 초기화해야함.

onCreateView()

프래그먼트에서 가장 중요한 콜백 함수 중 하나로 Fragment에서 그릴 View를 생성할 때 호출되는 함수로 이 함수에서는 View를 반환해야 함.

onActivityCreate()

acticity의 onCreate() 함수가 완료되고 나서 실행되는 함수로, acticity 생성 후 Fragment에서 해야할 작업이 있을 시 로직을 작성하는 곳이다.

onStart()

사용자에게 Fragment가 보이기 시작할 때 실행

onResume()

사용자와 상호작용할 수 있음. 사용자가 Fragment를 떠나지 않는 이상 계속 재개된 상태에 머물게 됨

onPause()

사용자가 프래그먼트를 떠날 때 처음 불러지는 콜백 함수. 이때 불필요한 리소스들 제거

onStop()

Fragment가 사용자에게 더 이상 보이지 않을 때 콜백 되는 함수

onDestoryView()

앞서 콜백 함수인 onCreateView()와 상응하는 함수로 뷰 리소스들을 해제

onDestory()

Fragement가 마지막으로 완전히 삭제되기 전에 호출되는 함수

onDetach()

앞서 onAttach() 콜백 함수와 상응되는 것으로서 액티비와의 연결을 끊기 전에 호출

예제 코드

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SideProject"
        tools:targetApi="31">
        <activity
            android:name=".presentation.TwoColorActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>

    </application>

</manifest>

XML

<!-- activity_two_color -->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".presentation.TwoColorActivity">

    <FrameLayout
        android:id="@+id/fragmentFrame"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="@color/tertiary_40"
        app:layout_constraintTop_toTopOf="parent"
        />

    <Button
        android:id="@+id/button_90_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_margin="10dp"
        android:text="Tertiary90 Fragment"/>
    <Button
        android:id="@+id/button_10_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@id/button_90_fragment"
        android:layout_margin="10dp"
        android:text="Tertiary10 Fragment"/>


</androidx.constraintlayout.widget.ConstraintLayout>
<!-- fragment_10 -->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tertiary_10">

</androidx.constraintlayout.widget.ConstraintLayout>
<!-- fragment_90 -->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tertiary_90">

</androidx.constraintlayout.widget.ConstraintLayout>

Fragment

package com.twent.sideproject.presentation.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.twent.sideproject.R

class Color10Fragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fregment_10 , container, false)
    }
}
package com.twent.sideproject.presentation.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.twent.sideproject.R

class Color90Fragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstaceState: Bundle?
    ): View? {
       return inflater.inflate(R.layout.fregment_90, container, false);
    }
}

Activity

package com.twent.sideproject.presentation

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.twent.sideproject.R
import com.twent.sideproject.presentation.fragment.Color10Fragment
import com.twent.sideproject.presentation.fragment.Color90Fragment

class TwoColorActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_two_color)

        settingButtons()
    }

    fun settingButtons() {
        val t10Button = findViewById<Button>(R.id.button_10_fragment)
        val t90Button = findViewById<Button>(R.id.button_90_fragment)

        t10Button.setOnClickListener{
            val fragmentTransaction =
                supportFragmentManager.beginTransaction()
            fragmentTransaction.replace(R.id.fragmentFrame, Color10Fragment())
            fragmentTransaction.commit()
        }
        t90Button.setOnClickListener{
            val fragmentTransaction =
                supportFragmentManager.beginTransaction()
            fragmentTransaction.replace(R.id.fragmentFrame, Color90Fragment())
            fragmentTransaction.commit()

        }
    }
}

0개의 댓글