안드로이드 코틀린 : 일반 클래스에서 Fragment의 메서드 사용하기
Lucy Archive
Lucy 2023
2021. 4. 17. 01:13

Android Kotlin : Access fragment method from other class

이 포스트는

일반 클래스에서 프래그먼트의 메서드를 호출 방법

에 대해 작성하였습니다.

 

일반 Class에서 Fragment 메서드 사용 방법

Fragment 코드(MyFragment.kt)

Fragment 클래스의 companion object{} 내에서 인스턴스를 변수를 선언하고 인스턴스를 반환하는 getInstance() 메서드를 등록합니다. init{} 에서 instance에 자신(this)을 입력합니다. 

  • init{...} : 클래스가 처음 생성될 때 실행되는 블록
  • companion object{...} : 클래스를 생성자로 인스턴스화 하지 않아도 블록 안의 프로퍼티와 메서드 사용 가능
package com.blacklog.fragmentmethod

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.blacklog.fragmentmethod.databinding.FragmentMyBinding

class MyFragment : Fragment() {

    private var _binding: FragmentMyBinding? = null
    private val binding get() = _binding!!


    init{
        instance = this
    }

    companion object{
        private var instance: MyFragment? = null
        fun getInstance():MyFragment?{
            return instance
        }
    }

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

        binding.button.setOnClickListener {
            val myClass = MyClass()
            myClass.toastHello()
        }
        return binding.root
    }

    fun hello(){
        Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show()
    }
}

※ MyClass.kt 클래스 코드를 등록하지 않은 경우 36, 37번 라인의 코드는 빨간색으로 표시됩니다. 13,14,33~35 의 binding 이 있는 코드는 ViewBinding 설정 코드로, ViewBinding 설정 법은 아래의 링크를 참조해주세요. 

안드로이드 View Binding

 

안드로이드 View Binding 사용하기 - kotlin-android-extensions 지원 중단

안드로이드 View Binding 방법 정리 안드로이드 코드에서 레이아웃 View에 접근하기 위해 사용된 kotlin-android-extensions 의 지원이 중단예정으로, 이를 대체하여 사용 할 수 있는 ViewBinding 사용법에 대해

juahnpop.tistory.com

참고로 위에서 생성된 MyFragment의 레이아웃 파일 fragment_my.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyFragment">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="22dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

일반 Class 코드(MyClass.kt)

MyClass 이름의 클래스를 생성 후 아래 코드와 같이 toastHello() 메서드에서 MyFragment의 hello() 메서드를 호출 합니다. 

package com.blacklog.fragmentmethod

class MyClass {
    fun toastHello(){
        MyFragment.getInstance()?.hello()
    }
}

 

실행 결과

위 코드를 실행하면 아래와 같이 Fragment에 있는 버튼 리스너에서 MyClass의 toastHello() 메서드를 생성 실행합니다. MyClass의 toastHello() 메서드는 MyFragment의 Hello() 메서드를 호출합니다.  

실행 결과

관련포스트

🤞 안드로이드(코틀린) 앱 제작하기 관련글 목록 보기

🤞 안드로이드(코틀린) 코틀린 : 클래스 관련글 목록 보기

🤞 안드로이드(코틀린) 프래그먼트 관련글 목록 보기