Android

Interface를 통한 Activity-Fragment간 통신

Dean83 2022. 6. 8. 17:35

사실 interface를 이용하면 어느 경우에서건 통신이 가능하다. 

주로 Activity에서 fragment를 사용하는 경우가 많기에 이 기준으로 테스트를 했다. 

 

1. 간략 설명
    - 인터페이스 및 함수 구현

    - fragment 클래스 내에 인터페이스 맴버변수 생성 및 특정상황에서 해당 변수 호출코드 작성
    - activity 클래스에 인터페이스 상속 및 함수 구현

    - activity에서 fragment의 인터페이스 맴버변수에 this를 통한 세팅

2. 인터페이스 구현

public interface FragInterface
{
    fun TestInterface()
}

3. Fragment에서 인터페이스 맴버변수 설정 및 특정상황에서 해당 변수 호출

//인터페이스 형 맴버변수 선언
lateinit var interfaceTest : FragInterface

....

//액티비티를 인자값으로 받아, 맴버변수에 반영하는 코드
public fun setInterface(item : FragInterface)
{
    interfaceTest = item
}

....

// 특정상황에서 인터페이스 호출
interfaceTest?.TestInterface()

4. Activity에서 interface상속 및 함수 구현

class MainActivity : AppCompatActivity(), FragInterface {

...

    //인터페이스 구현
    override fun TestInterface() {
        Log.d("test","aa")
    }

}

5. Activity에서 fragment 맴버변수 설정 (인터페이스 변수)
    - 다양한 방법이 있으나, fragmentManager를 통해 onAttachFragment 함수에서 설정함.

onCreate함수에서, 
fragManager = supportFragmentManager
fragManager.addFragmentOnAttachListener(this)


override fun onAttachFragment(
    fragmentManager: FragmentManager,
    fragment: androidx.fragment.app.Fragment
) {

    if(fragment is 프래그먼트 클래스명)
    {
        //setInterface는 예시임. 
        (fragment as 프래그먼트 클래스명).setInterface(this)
    }

}

 

요약하자면, 

- 인터페이스 생성

- 프래그먼트에서 인터페이스 변수 생성

- activity에서 인터페이스 상속 및 구현

- activity에서 프래그먼트의 인터페이스 변수에 자신을 넣음

- 프래그먼트에서 필요에 따라 인터페이스 변수 함수 호출시, activity의 인터페이스 구현부가 호출됨