viewBinding+kotlin 202106

Activity

open class BaseActivity: AppCompatActivity() {
    lateinit var binding:T
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val cls = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class
        binding = cls.getMethod("inflate", LayoutInflater::class.java).invoke(null, LayoutInflater.from(this)) as T
        setContentView(binding.root)
    }
}

class MainActivity:BaseActivity() {

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

Fragment

open class BaseFragment : Fragment() {
    private var _binding:T? = null
    val binding get() = _binding!!

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val cls = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class
        _binding = cls.getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java).invoke(null, LayoutInflater.from(requireActivity()), container, false) as T
        return binding.root
    }

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

class HomeFragment:BaseFragment() {

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

View

class XxxView : ConstraintLayout {
    lateinit var binding:XxxxxBinding

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context,  attrs, defStyleAttr)

    init {
        val root = inflate(context, R.layout.xxx, this)
        binding = XxxxxBinding.bind(root)
        initView()
    }

    private fun initView() {
        binding.tv.text = "hehe"
    }

混淆

-keep class * implements androidx.viewbinding.ViewBinding
-keepclassmembers class * implements androidx.viewbinding.ViewBinding { public static ** inflate(...); public static ** bind(***); }

你可能感兴趣的:(viewBinding+kotlin 202106)