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

Fragment 사용법 (2) Activity와 데이터 주고받기

2020. 4. 30.

파일 구조

 

Acvitity 컴포넌트 트리

plain Text -> id: inputText

button -> id: sendButton

text -> id: fragmentText

frameLayout -> id: content

 

Fragment 컴포넌트 트리

text -> id: activityText

button -> id: confirmButton

 

Activity 코드

package com.example.myexam1

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

class MainActivity : AppCompatActivity(){

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

        sendButton.setOnClickListener{
            val fragment = supportFragmentManager.findFragmentById(R.id.content)
            if(fragment is ContentFragment){
                fragment.setActivityText(inputText.text.toString())
            }
        }

        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.content,ContentFragment())
        transaction.commit()
    }

    override fun onAttachFragment(fragment: Fragment) {
        super.onAttachFragment(fragment)
        if(fragment is ContentFragment){
            fragment.onInputTextListener = object : ContentFragment.OnInputTextListener{
                override fun onInputText(text: String?) {
                    fragmentText.text = text
                }

            }
        }
    }
}

 

Fragment 코드

package com.example.myexam1

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

/**
 * A simple [Fragment] subclass.
 */
class ContentFragment : Fragment() {

    interface OnInputTextListener{
        fun onInputText(text:String?)
    }

    var onInputTextListener: OnInputTextListener? = null

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        confirmButton.setOnClickListener{
            onInputTextListener?.onInputText("확인되었습니다")
        }
    }

    fun setActivityText(text: String?){
        activityText.text = text
    }

}