안드로이드(Kotlin)/기초/

Fragment 사용법 (1) 기본

2020. 4. 30.

파일 구조

 

Main 컴포넌트 트리

button1 -> id: firstButton, text: Fragment1

button2 -> id: secondButton, text: Fragment2

frameLayout -> id: content

 

Fragment

FirstFragment -> background: #FFFF0000

SecondFragment -> background: #FF0000FF

 

코드

package com.example.myexam1

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)

        firstButton.setOnClickListener{
            val transaction = supportFragmentManager.beginTransaction()
            transaction.replace(R.id.content,FirstFragment())
            transaction.commit()
        }

        secondButton.setOnClickListener{
            val transaction = supportFragmentManager.beginTransaction()
            transaction.replace(R.id.content,SecondFragment())
            transaction.commit()
        }
    }
}