Android Kotlin Viewbinding封装

目录

Viewbinding配置

Activity封装

Activity使用

Fragment封装

Fragment使用

Dialog封装

Dialog使用


Viewbinding配置

android { 
   viewBinding { enabled = true } 
} 

Activity封装

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding

/**
 * @explain
 * @author Created by PGC on 2023/12/11 9:56.
 */
abstract class BaseBindingActivity(private val inflate: (LayoutInflater) -> VB) : AppCompatActivity() {

    lateinit var binding: VB

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

}

Activity使用

class ExampleActivity : BaseBindingActivity(ActivityExampleBinding::inflate) {
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.exampleBindingBt.text = "binding"
    }
}

Fragment封装

abstract class BaseBindingFragment(private val inflater: (LayoutInflater, ViewGroup?, Boolean) -> VB) :
    Fragment() {

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

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

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

}

Fragment使用

class ExampleFragment : BaseBindingFragment(FragmentExampleBinding::inflate) {

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.exampleBindingTv.text="binding"
    }
}

Dialog封装

abstract class BaseBindingDialog(context: Context,themeResId: Int,private val inflate: (LayoutInflater) -> VB) : Dialog(context, themeResId) {

  lateinit var binding: VB

  constructor(context: Context, inflate: (LayoutInflater) -> VB) : this(context, 0, inflate)

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

Dialog使用

class ExampleDialog(context: Context): BaseBindingDialog(context,0,DialogExampleBinding::inflate) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.tv.text = "binding"
    }
}

你可能感兴趣的:(我的Android之路,android,kotlin,封装,android,jetpack)