티스토리 뷰
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_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>
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>
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_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>
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>
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()
}
}
}
'Android > Kotlin' 카테고리의 다른 글
[Kotlin] Fragment에서 Child Fragment로 데이터 전달 (0) | 2020.10.24 |
---|---|
[Kotlin] Fragment 간의 데이터 전달 (0) | 2020.10.24 |
[Kotlin] Activity에서 Fragment로 데이터 전달 (0) | 2020.10.24 |
[Kotlin] Activity 간의 데이터 전달 (0) | 2020.10.24 |
[Kotlin] savedInstanceState를 이용하여 Activity 데이터 보존하기 (0) | 2020.10.15 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Livedata
- coroutine
- James Kim
- Design Pattern
- Android
- Vue.js #Vue.js + javascript
- Kotlin
- 코틀린
- java
- ViewModel
- handler
- 안드로이드
- ArrayList
- 혀가 길지 않은 개발자
- Intent
- DataBinding
- 안드로이드 #코틀린 #Android #Kotlin
- ViewPager2
- MVVM
- JSONObject
- TabLayout
- activity
- XML
- 자바
- fragment
- JSONArray
- View
- CoordinatorLayout
- Architecture Pattern
- recyclerview
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함