티스토리 뷰

Android/Kotlin

[Kotlin]  Fragment에서 Activity로 데이터 전달

혀가 길지 않은 개발자 2020. 10. 24. 17:18

1. Interface를 이용하는 방법

2. ViewModel을 공유하는 방법


1. Interface를 이용하는 방법

 

fragment_red.xml

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFBBBB">

    <Button
        android:id="@+id/btnSendToMain"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:textAllCaps="false"
        android:text="Send To Main"
        android:textSize="24dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

fragment_red.xml

 

 

 

 

fragment_green.xml

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#BBFFBB">

    <Button
        android:id="@+id/btnSendToMain"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:textAllCaps="false"
        android:text="Send To Main"
        android:textSize="24dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

fragment_green.xml

 

 

 

activity_main.xml

<?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"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textAlignment="center"
        android:textSize="26dp"
        android:textStyle="bold|italic"
        tools:text="main"/>

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <Button
        android:id="@+id/btnChange"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:textAllCaps="false"
        android:text="Change Fragment"
        android:textSize="22dp"/>

</LinearLayout>

activity_main.xml

 

 

 

 

FragmentRed.kt

package com.jwsoft.kotlinproject

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

class FragmentRed : Fragment() {

    private var mOnListenerRed: OnListenerRed? = null

    interface OnListenerRed {
        fun onReceivedData(name: String)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mOnListenerRed = activity as OnListenerRed
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        btnSendToMain.setOnClickListener {
            mOnListenerRed?.onReceivedData("FragmentRed -> MainActivity")
        }
    }

    override fun onDetach() {
        super.onDetach()
        mOnListenerRed = null
    }
}

 

 

 

 

FragmentGreen.kt

package com.jwsoft.kotlinproject

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

class FragmentGreen : Fragment() {

    private var mOnListenerGreen: OnListenerGreen? = null

    interface OnListenerGreen {
        fun onReceivedData(name: String)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mOnListenerGreen = activity as OnListenerGreen
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        btnSendToMain.setOnClickListener {
            mOnListenerGreen?.onReceivedData("FragmentGreen -> MainActivity")
        }
    }

    override fun onDetach() {
        super.onDetach()
        mOnListenerGreen = null
    }
}

 

 

 

 

MainActivity.kt

package com.jwsoft.kotlinproject

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

class MainActivity : AppCompatActivity(), FragmentRed.OnListenerRed, FragmentGreen.OnListenerGreen {

    private val fragmentManager = supportFragmentManager
    private lateinit var transaction: FragmentTransaction
    private var isRed = false

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

        transaction = fragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, FragmentRed())
        transaction.add(R.id.frameLayout, FragmentGreen())
        transaction.commit()

        btnChange.setOnClickListener {

            transaction = fragmentManager.beginTransaction()

            if (isRed) {
                transaction.replace(R.id.frameLayout, FragmentGreen())
            } else {
                transaction.replace(R.id.frameLayout, FragmentRed())
            }

            isRed = !isRed
            transaction.commit()

        }

    }

    override fun onReceivedData(name: String) {
        tvMain.text = name
    }

}

실행 결과

 

 

 

 


2. ViewModel을 공유하는 방법

 

fragment_red.xml

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFBBBB">

    <Button
        android:id="@+id/btnSendToMain"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:textAllCaps="false"
        android:text="Send To Main"
        android:textSize="24dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

fragment_red.xml

 

 

 

fragment_green.xml

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#BBFFBB">

    <Button
        android:id="@+id/btnSendToMain"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:textAllCaps="false"
        android:text="Send To Main"
        android:textSize="24dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

fragment_green.xml

 

 

 

 

activity_main.xml

<?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"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textAlignment="center"
        android:textSize="26dp"
        android:textStyle="bold|italic"
        tools:text="main"/>

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <Button
        android:id="@+id/btnChange"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:textAllCaps="false"
        android:text="Change Fragment"
        android:textSize="22dp"/>

</LinearLayout>

activity_main.xml

 

 

 

 

ActivityViewModel.kt

package com.jwsoft.kotlinproject

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class ActivityViewModel : ViewModel() {

    var mainText: MutableLiveData<String> = MutableLiveData()

}

 

 

 

 

FragmentRed.kt

package com.jwsoft.kotlinproject

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

class FragmentRed : Fragment() {

    private lateinit var viewModel: ActivityViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProvider(requireActivity(), ViewModelProvider.NewInstanceFactory())
            .get(ActivityViewModel::class.java)

        return inflater.inflate(R.layout.fragment_red, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        btnSendToMain.setOnClickListener {
            viewModel.mainText.value = "FragmentRed -> Main"
        }
    }

}

 

 

 

 

FragmentGreen.kt

package com.jwsoft.kotlinproject

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

class FragmentGreen : Fragment() {

    private lateinit var viewModel: ActivityViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProvider(requireActivity(), ViewModelProvider.NewInstanceFactory())
            .get(ActivityViewModel::class.java)

        return inflater.inflate(R.layout.fragment_green, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        btnSendToMain.setOnClickListener {
            viewModel.mainText.value = "FragmentGreen -> Main"
        }
    }

}

 

 

 

 

MainActivity.kt

package com.jwsoft.kotlinproject

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: ActivityViewModel
    private val fragmentManager = supportFragmentManager
    private lateinit var transaction: FragmentTransaction
    private var isRed = false

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

        viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory())
            .get(ActivityViewModel::class.java)

        transaction = fragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, FragmentRed())
        transaction.add(R.id.frameLayout, FragmentGreen())
        transaction.commit()

        viewModel.mainText.observe(this, Observer {
            tvMain.text = it
        })

        btnChange.setOnClickListener {

            transaction = fragmentManager.beginTransaction()

            if (isRed) {
                transaction.replace(R.id.frameLayout, FragmentGreen())
            } else {
                transaction.replace(R.id.frameLayout, FragmentRed())
            }

            isRed = !isRed
            transaction.commit()

        }

    }

}

실행 결과

 

 

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함