본문 바로가기

[Android/Kotlin] 안드로이드 ViewBinding with BaseActivity, BaseFragment

꿈꾸는블로그왕 2021. 2. 6.

안녕하세요. 오늘은 BaseActivity 클래스와 BaseFragment 클래스를 사용하여 좀 더 편안하게 ViewBinding을 사용하는 방법에 대해서 알아보겠습니다.

 

액티비티와 프레그먼트가 많아질수록 ViewBinding을 초기 세팅하는 일도 만만치 않습니다.

초기 세팅을 Base 추상 클래스에서 구현하도록 하겠습니다.

 

BaseActivity에서 구현하는 방법입니다.

 

[BaseActivity.kt]

abstract class BaseActivity<B: ViewBinding>(
    val bindingFactory: (LayoutInflater) -> B
): AppCompatActivity() {

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = bindingFactory(layoutInflater)
        setContentView(binding.root)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}

 

사용방법은 아래와 같습니다.

[MainActivity.kt]

class MainActivity : BaseActivity<MainActivityBinding>({ MainActivityBinding.inflate(it)}) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.appBarMain.fabCreateBoard.setOnClickListener {
            val intent = CreateBoardActivity.start(this, userName)
            startActivityForResult(intent, CREATE_BOARD_REQUEST_CODE)
        }
    }

}

 

 

BaseFragment에서 구현하는 방법입니다.

[BaseFragment.kt]

abstract class BaseFragment<B: ViewBinding>: Fragment() {

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

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = getFragmentBinding(inflater, container)
        return binding.root
    }

    abstract fun getFragmentBinding(inflater: LayoutInflater, container: ViewGroup?): B

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

 

사용방법은 아래와 같습니다.

[SplashFragment.kt]

class SplashFragment : BaseFragment<SplashFragmentBinding>() {

    override fun getFragmentBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): SplashFragmentBinding {
        return SplashFragmentBinding.inflate(inflater, container, false)
    }

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

        Handler(Looper.getMainLooper()).postDelayed({
            if (isOnBoardingFinished()) {
                findNavController().navigate(R.id.action_splashFragment_to_homeFragment)
            } else {
                findNavController().navigate(R.id.action_splashFragment_to_onBoardingFragment)
            }
        }, 1500)
    }

    private fun isOnBoardingFinished(): Boolean {
        val prefs = requireActivity().getSharedPreferences("onBoarding", Context.MODE_PRIVATE)
        return prefs.getBoolean("finished", false)
    }

}

 

댓글