Kotlin ViewDatabinding 的基类
BaseActivity
abstract class BaseActivity<VIEW: ViewBinding> : AppCompatActivity() {
var mBinding : VIEW ?= null
private val binding get() = mBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = viewBinding(layoutInflater)
val rootView = binding?.root
setContentView(rootView)
}
override fun onStart() {
super.onStart()
initUI()
initListener()
}
abstract fun viewBinding(layoutInflater: LayoutInflater): VIEW?
abstract fun initUI()
abstract fun initListener()
override fun onDestroy() {
super.onDestroy()
mBinding = null
}
}
BaseActivity使用方式 ActiviytFragmentAnimationsBinding 为 activiyt_fragment_animations.xml对应生成
class MainActivity : BaseActivity<ActiviytFragmentAnimationsBinding>() {
private val TAG = "MainActivity"
override fun viewBinding(layoutInflater: LayoutInflater): ActiviytFragmentAnimationsBinding? {
return ActiviytFragmentAnimationsBinding.inflate(layoutInflater)
}
override fun initUI() {
mBinding!!.tv_test.text = "test"
}
override fun initListener() {
}
override fun onStart() {
super.onStart()
}
}
BaseFragment
abstract class BaseFragment<VIEW : ViewBinding>:Fragment() {
var mBinding : VIEW ?= null
private val binding get() = mBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mBinding = viewBinding(inflater,container)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initListener()
initUI()
}
abstract fun viewBinding(inflater: LayoutInflater, container: ViewGroup?): VIEW
override fun onStart() {
super.onStart()
}
abstract fun initUI()
abstract fun initListener()
override fun onDestroyView() {
super.onDestroyView()
mBinding = null
}
BaseFragment使用方法 用法和Activity一样
class FragmentNetWork : BaseFragment<FragmentNetworkBinding>() {
override fun viewBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentNetworkBinding {
return FragmentNetworkBinding.inflate(inflater, container, false)
}
override fun initUI() {
}
override fun initListener() {
}
override fun onDestroy() {
super.onDestroy()
mBinding = null
}
}
|