본문 바로가기
앱 개발일지

[Android / Kotlin] 프래그먼트

by developer jini 2022. 7. 11.
728x90

Fragment 클래스 생성

package com.example.ch10

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup


class BlankFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false)
    }

}

mainActivity 클래스

package com.example.ch10

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction


class MainActivity : AppCompatActivity() {

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

        val fragmentManager : FragmentManager = supportFragmentManager
        val transaction : FragmentTransaction = fragmentManager.beginTransaction()
        val fragment = BlankFragment()
        transaction.add(R.id.container,fragment)
        transaction.commit()
    }


}

add 함수( int 컨테이너뷰ID , 프래그먼트) 

commit : 화면에 적용

 

<레이아웃 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:id="@+id/container"
    android:orientation="vertical">

<fragment
    android:name="com.example.ch10.BlankFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>


</LinearLayout>

name 속성에 프래그먼트 클래스 등록.

728x90

댓글