Android Kotlin Viewbinding封装

发布时间:2023年12月17日

目录

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<VB : ViewBinding>(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>(ActivityExampleBinding::inflate) {
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.exampleBindingBt.text = "binding"
    }
}

Fragment封装

abstract class BaseBindingFragment<VB : ViewBinding>(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>(FragmentExampleBinding::inflate) {

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

Dialog封装

abstract class BaseBindingDialog<VB : ViewBinding>(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<DialogExampleBinding>(context,0,DialogExampleBinding::inflate) {

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

文章来源:https://blog.csdn.net/pengguichu/article/details/134921228
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。