目录
android {
viewBinding { enabled = true }
}
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)
}
}
class ExampleActivity : BaseBindingActivity<ActivityExampleBinding>(ActivityExampleBinding::inflate) {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.exampleBindingBt.text = "binding"
}
}
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
}
}
class ExampleFragment : BaseBindingFragment<FragmentExampleBinding>(FragmentExampleBinding::inflate) {
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.exampleBindingTv.text="binding"
}
}
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)
}
}
class ExampleDialog(context: Context): BaseBindingDialog<DialogExampleBinding>(context,0,DialogExampleBinding::inflate) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.tv.text = "binding"
}
}