Android/Kotlin

Activity - Fragment 간 Communication

lipnus 2019. 3. 13. 14:05
반응형

1. Fragment -> Activity

fragment의 버튼을 누르면 "까꿍" string이 activity의 TextView에 표시



TestFragment.kt

class TestFragment : Fragment() {

private lateinit var fragment_btn: Button
private lateinit var fragment_tv: TextView

private var listener: OnFragmentInteractionListener? = null

override fun onAttach(context: Context) {
super.onAttach(context)

if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}

...



override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_test, container, false)
fragment_tv = view.findViewById(R.id.fragment_tv)

fragment_btn.setOnClickListener {
istener?.onFragmentInteraction(msg)
}
return view
}

interface OnFragmentInteractionListener {
// TODO: Update argument type and name
fun onFragmentInteraction(msg: String)
}


MainActivity.kt

class MainActivity : AppCompatActivity(), TestFragment.OnFragmentInteractionListener {



override fun onFragmentInteraction(msg: String) {
activity_tv.text = msg
}

private val fragment: TestFragment by lazy { TestFragment() }

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

//프레그먼트
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit()

}
}




2. Activity -> Fragment

activity의 버튼 누르면 Fragment의 textview에 "까꿍!"표시.

프레그먼트에 함수 하나 만든 다음에 Activity에서 호출하면 된다.


//프레그먼트의 함수호출
activity_btn.setOnClickListener {
fragment.setMsg("까꿍!")
}

activity에서 호출


fun setMsg(msg:String){
fragment_tv.text = msg
}

fragment의 함수








전체코드



MainActivity

class MainActivity : AppCompatActivity(), TestFragment.OnFragmentInteractionListener {


//프레그먼트에서 온 값
override fun onFragmentInteraction(msg: String) {
activity_tv.text = msg
}

private val fragment: TestFragment by lazy { TestFragment() }

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

//프레그먼트
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit()


//프레그먼트의 함수호출
activity_btn.setOnClickListener {
fragment.setMsg("까꿍!")
}

}
}



TestFragment (Android Stuio에서 BlankFragmnet로 생성된 코드 기반)


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [BlankFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [BlankFragment.newInstance] factory method to
* create an instance of this fragment.
*
*/


class TestFragment : Fragment() {

private lateinit var fragment_btn: Button
private lateinit var fragment_tv: TextView

// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var listener: OnFragmentInteractionListener? = null


override fun onAttach(context: Context) {
super.onAttach(context)

if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_test, container, false)

fragment_btn = view.findViewById(R.id.fragment_btn)
fragment_tv = view.findViewById(R.id.fragment_tv)

fragment_btn.setOnClickListener {
onButtonPressed("까꿍")
}
return view
}

// TODO: Rename method, update argument and hook method into UI event
fun onButtonPressed(msg: String) {
listener?.onFragmentInteraction(msg)
}


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


fun setMsg(msg:String){
fragment_tv.text = msg
}


/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments]
* (http://developer.android.com/training/basics/fragments/communicating.html)
* for more information.
*/
interface OnFragmentInteractionListener {

fun onFragmentInteraction(msg: String)
}


companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
TestFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}


반응형

'Android > Kotlin' 카테고리의 다른 글

ViewPager 예제  (0) 2019.03.14
RecyclerView Click이벤트 구현  (0) 2019.03.14
@JvmStatic (자바,코틀린 static매소드 연동)  (0) 2019.03.13
클립보드 복사  (0) 2019.03.08
Dialog  (0) 2019.02.27