Android의 'Fragment'는 하위 활동입니다. 단일 '액티비티'는 여러 프래그먼트를 호스팅할 수 있습니다. 예를 들어 하위 페이지가 있는 하나의 기본 페이지가 필요한 경우 Fragments에 대해 생각해야 합니다. 흥미로운 점은 프래그먼트에는 자체 수명 주기가 있으므로 활동에 크게 의존하지 않고도 독립적인 작업 방식을 제공한다는 것입니다.

이 튜토리얼은 Kotlin Android 기반의 간단한 HowTo 예제를 통해 프래그먼트를 사용하는 방법을 알려줍니다.

예제 1: Kotlin Android - ActivityFragment 표시

활동에는 클릭하면 조각이 표시되는 버튼이 있습니다. 다음은 생성된 데모 이미지입니다.

코틀린 안드로이드 프래그먼트 예시

1단계: 종속성

이 프로젝트에는 타사 종속성이 필요하지 않습니다.

2단계: 레이아웃 디자인

두 개의 레이아웃이 필요합니다. 하나는 프래그먼트용이고 다른 하나는 메인 액티비티용입니다.

(ㅏ). 조각.xml

이것은 프래그먼트의 레이아웃입니다. 그것은 단순히 textiew를 포함할 것입니다:

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

    <TextView
        android:id="@+id/txt_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top|left"
        android:text="@string/str_fragment"
        android:textColor="#2a2a2a"
        android:layout_margin="10dp"
        android:padding="10dp"/>

</LinearLayout>

(비). 활동_메인.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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.9"
        android:text="@string/show"/>

    <FrameLayout
        android:id="@+id/fragment_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.1">

    </FrameLayout>
</LinearLayout>

3단계: 프래그먼트 생성

세 번째 단계는 실제 조각을 만들고 레이아웃을 확장하는 것입니다. 프래그먼트는 androidx.fragment.app.Fragment 클래스를 확장하여 생성됩니다. 'onCreateView()'를 재정의하고 프래그먼트의 레이아웃에서 확장된 뷰 객체를 반환하여 확장됩니다.

전체 코드는 다음과 같습니다.

Fragment_one.kt


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment.*

class Fragment_one : Fragment() {

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        txt_fragment.setOnClickListener {
            Toast.makeText(activity,"text fragment",Toast.LENGTH_SHORT).show()
        }

    }

}

4단계: MainActivity 만들기

이것은 프래그먼트를 호스팅할 활동입니다. 프래그먼트는 자체적으로 존재하지 않지만 활동에 의해 호스팅됩니다. 단일 활동은 여러 조각을 호스팅할 수 있습니다.

액티비티 내부의 프래그먼트를 표시하려면 프래그먼트 트랜잭션이라고 하는 작업을 수행해야 합니다. 이러한 트랜잭션은 프래그먼트 추가, 프래그먼트 제거, 프래그먼트 교체 등이 될 수 있습니다. 우리의 경우 프레임 레이아웃을 프래그먼트로 교체하는 데 관심이 있습니다. 이를 수행하는 코드는 다음과 같습니다.


    fun showFragment(fragment: Fragment_one){
        val fram = supportFragmentManager.beginTransaction()
        fram.replace(R.id.fragment_main,fragment)
        fram.commit()
    }

이 활동의 ​​전체 코드는 다음과 같습니다.

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_show.setOnClickListener {

            val fragment = arb.test.fragment.Fragment_one()
            showFragment(fragment)

        }

    }

    fun showFragment(fragment: Fragment_one){
        val fram = supportFragmentManager.beginTransaction()
        fram.replace(R.id.fragment_main,fragment)
        fram.commit()
    }
}

운영

이제 프로젝트를 실행합니다.

참조

아래 코드를 다운로드하세요.

번호 링크
1. 다운로드 코드
2. 팔로우 코드 작성자

예제 2: Kotlin Android 프래그먼트 수명 주기

Fragment에서 수명 주기 이벤트를 처리하는 방법을 알려주는 프로젝트입니다.

1단계: 프로젝트 생성

빈 'Android Studio' 프로젝트를 생성하여 시작합니다.

2단계: 종속성

타사 종속성이 필요하지 않습니다.

3단계: 레이아웃 디자인

우리는 세 개의 레이아웃이 필요합니다: 두 개의 프래그먼트를 위한 두 개와 Activity를 위한 하나:

(ㅏ). fragment_first.xml

이 레이아웃에 여러 TextView를 추가합니다. 이 레이아웃은 첫 번째 Fragment로 확장됩니다.

<?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:orientation="vertical"
    tools:context=".FirstFragment">

    <TextView
        android:id="@+id/firstFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/first_fragment"
        android:textColor="@color/colorPrimary"/>

    <TextView
        android:id="@+id/txtUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/colorPrimary"/>

    <TextView
        android:id="@+id/txtLastName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/colorPrimary"/>
</LinearLayout>

(비). fragment_second.xml

이 레이아웃에 버튼을 추가하고 텍스트를 편집하세요. 이것은 두 번째 Fragment의 레이아웃입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <EditText
        android:id="@+id/edtUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:textColor="#FF0000"
        android:hint="@string/enter_name"
        android:inputType="textPersonName" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtLastName"
        android:textColor="#FF0000"
        android:hint="@string/enter_last_name"
        android:autofillHints=""
        android:inputType="textPersonName" />
    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show_details"/>
</LinearLayout>

(씨). 활동_메인.xml

이 레이아웃에 Fragment 요소를 추가합니다. 이것은 MainActivity의 레이아웃입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:name="com.example.lifecycle.SecondFragment"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_below="@id/fragment_container"
        android:layout_marginTop="329dp"
        android:background="@color/black" />

    <fragment
        android:id="@+id/first_fragment"
        android:name="com.example.lifecycle.FirstFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/divider"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="187dp" />

</RelativeLayout>

4단계: 첫 번째 조각 만들기

Fragment의 수명 주기 메서드를 재정의합니다.

이 조각의 코드는 다음과 같습니다.

FirstFragment.kt

package com.example.lifecycle

import android.content.ContentValues.TAG
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView

class FirstFragment : Fragment() {
    var TAG = "ActivityLifeCycle"
    lateinit var firstnameTxt : TextView
    lateinit var lastnameTxt : TextView
    override fun onAttach(context: Context) {
        super.onAttach(context)
        Log.d(TAG, "===>fragment===>onAttach()")
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "===>fragment===>onCreate()")
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        Log.d(TAG, "===>fragment===>onCreateView()")
        val view = inflater.inflate(R.layout.fragment_first, container, false)
        firstnameTxt = view.findViewById<TextView>(R.id.txtUsername)
        lastnameTxt = view.findViewById<TextView>(R.id.txtLastName)
        return view
    }
    fun showDetails(firstName:String, lastName:String){
        firstnameTxt.text = firstName
        lastnameTxt.text = lastName
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        Log.d(TAG, "===>fragment===>onActivityCreated()")
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "===>fragment===>onStart()")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "===>fragment===>onResume()")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "===>fragment===>onPause()")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "===>fragment===>onStop()")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d(TAG, "===>fragment===>onDestroyView()")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "===>fragment===>onDestroy()")
    }

    override fun onDetach() {
        super.onDetach()
        Log.d(TAG, "===>fragment===>onDetach()")
    }

}

5단계: 두 번째 조각 만들기

두 번째 조각을 만들고 다음 코드를 추가합니다.

SecondFragment.kt

package com.example.lifecycle

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_second.*

class SecondFragment : Fragment() {

    interface GetUserDetail{
        fun showDetails(firstName:String, lastName:String)
    }
    lateinit var getUserDetail : GetUserDetail
    lateinit var firstNameEditText : EditText
    lateinit var lastNameEditText: EditText

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_second, container, false)
        val showButton = view.findViewById<Button>(R.id.btnShow)
        firstNameEditText = view.findViewById(R.id.edtUsername)
        lastNameEditText = view.findViewById(R.id.edtLastName)
        showButton.setOnClickListener(View.OnClickListener {
            getUserDetail.showDetails(firstNameEditText.text.toString(),lastNameEditText.text.toString())
        })
        return view
        }
}

6단계: MainActivity 만들기

프래그먼트는 활동에서 호스팅되어야 합니다. 두 조각을 모두 호스팅하는 것은 이 MainActivity입니다.

Fragment.kt

package com.example.lifecycle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.fragment.app.FragmentManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), SecondFragment.GetUserDetail {

    var TAG = "ActivityLifeCycle"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.d(TAG, "===>onCreate()")
        loadFragment()
    }
    private fun loadFragment()
    {
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        val secondFragment = SecondFragment()
        secondFragment.getUserDetail = this
        fragmentTransaction.add(R.id.fragment_container,secondFragment)
        fragmentTransaction.commit()
    }
    override fun onStart() {
        super.onStart()
        Log.d(TAG, "===>onStart()")
    }
    override fun onResume() {
        super.onResume()
        Log.d(TAG, "===>onResume()")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "===>onPause()")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "===>onStop()")
    }

    override fun onRestart() {
        super.onRestart()
        Log.d(TAG, "===>onRestart()")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "===>onDelete()")
    }

    override fun showDetails(firstName: String, lastName: String) {
        val firstFragment:FirstFragment = first_fragment as FirstFragment
        firstFragment.showDetails(firstName, lastName)
    }
}

운영

코드를 복사하거나 아래 링크에서 다운로드하여 빌드하고 실행합니다.

참조

참조 링크는 다음과 같습니다.

번호 링크
1. 다운로드 예제
2. 팔로우 코드 작성자

예제 3: 활동 내부의 Android 단순 조각

이것은 Activity 내부의 또 다른 간단한 Fragment입니다. 그러나 이번에는 Java로 코드를 작성합니다. 또한 Activity와 무관한 Fragment 내부의 위젯으로 작업하는 방법도 살펴보겠습니다.

시작하자.

1단계: 프로젝트 생성

빈 'Android Studio' 프로젝트를 생성하여 시작합니다.

2단계: 종속성

외부 또는 특수 종속성이 필요하지 않습니다.

3단계: 레이아웃 디자인

두 개의 레이아웃이 필요합니다. 하나는 Fragment용이고 다른 하나는 Activity용입니다.

(ㅏ). fragment_simple.xml

이 레이아웃 안에 Button, EditText 및 TextView와 같은 위젯을 추가합니다. 이 레이아웃은 Fragment로 확장됩니다.

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10" android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/textView1" android:layout_alignEnd="@+id/textView1">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" android:layout_below="@+id/editText1"
        android:layout_alignParentLeft="true" android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/editText1" android:layout_alignEnd="@+id/editText1"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView1"
        android:layout_below="@+id/button1" android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true" android:layout_alignParentBottom="true"
        android:background="#ff7299ff"/>

</RelativeLayout>

(비). 활동_메인.xml

이것은 MainActivity 레이아웃입니다. 이 활동이 Fragment를 호스팅한다는 점을 감안할 때 내부에 Fragment 태그를 추가해야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center_horizontal"
              android:orientation="vertical"
              android:padding="4dip" >

    <fragment
        android:id="@+id/FrameLayout1"
        android:name="com.example.ankitkumar.singlescreenfragment.MainActivity"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" >
    </fragment>

</LinearLayout>

4단계: 코드 작성

전체 코드는 다음과 같습니다.

MainActivity.java

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    int i = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        getFragmentManager().findFragmentById(R.id.FrameLayout1);

    }

    public static class SimpleAddition extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_simple, container, false);

            Button b = (Button) v.findViewById(R.id.button1);
            final EditText et1 = (EditText) v.findViewById(R.id.editText1);
            final TextView tv = (TextView) v.findViewById(R.id.textView1);

            b.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    tv.setText(et1.getText().toString());
                }
            });
            return v;
        }
    }

}

운영

코드를 복사하거나 아래 링크에서 다운로드하여 빌드하고 실행합니다.

참조

참조 링크는 다음과 같습니다.

번호 링크
1. 다운로드 예제
2. 팔로우 코드 작성자

Categorized in: