美文网首页
ViewBinding

ViewBinding

作者: 安卓_背包客 | 来源:发表于2021-09-15 20:03 被阅读0次

    使用

       buildFeatures {
            viewBinding=true
        }
    

    这样你就可以是使用了

    例如:

    • 你的Activity
    class MainActivity : AppCompatActivity() {
        lateinit var mainBinding: ActivityMainBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            mainBinding= ActivityMainBinding.inflate(layoutInflater)
            setContentView(mainBinding.root)
            
        }
    }
    
    • 你的fragment
    class FragmentOne : Fragment() {
         lateinit var fragmentOneBinding: FragmentOneBinding
        private var param1: String? = null
        private var param2: String? = null
        companion object {
            @JvmStatic
            fun newInstance(param1: String, param2: String) =
                FragmentOne().apply {
                    arguments = Bundle().apply {
                        putString(ARG_PARAM1, param1)
                        putString(ARG_PARAM2, param2)
                    }
                }
        }
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            arguments?.let {
                param1 = it.getString(ARG_PARAM1)
                param2 = it.getString(ARG_PARAM2)
            }
        }
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            fragmentOneBinding= FragmentOneBinding.inflate(layoutInflater,container,false)
            return fragmentOneBinding.root
        }
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            fragmentOneBinding.btnStartFragmentTwo.setOnClickListener {
                it.findNavController().navigate(R.id.action_fragmentOne_to_fragmentTwo)
            }
        }
    
    

    里面没有findviewbyid 了,这样就避免了null指针异常了

    下面我们就开始做一个简单的封装
    基类Activity

    abstract class BaseActivity<T : ViewBinding> : AppCompatActivity() {
        protected lateinit var viewBinding: T
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
          //  ParameterizedType 表示参数化类型,带有类型参数的类型,即常说的泛型,如:List<T>、Map<Integer, String>、List<? extends Number>。
            val pt = javaClass.genericSuperclass as ParameterizedType
           
            val cla = pt.actualTypeArguments[0] as Class<*>
            try {
               //通过反射加载类的inflate方法
                val declaredMethod = cla.getDeclaredMethod("inflate", LayoutInflater::class.java)
               //通过调用对应方法并强转成T
               viewBinding = declaredMethod.invoke(null, layoutInflater) as T
                setContentView(viewBinding.root)
                initCreate()
            } catch (e: NoSuchMethodException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            } catch (e: InvocationTargetException) {
                e.printStackTrace()
            }
        }
    
        abstract fun initCreate()
    }
    

    基类Fragment

    abstract class BaseFragment<T : ViewBinding> : Fragment() {
        protected lateinit var viewBinding: T
        abstract fun initCreateView(savedInstanceState: Bundle?)
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            try {
                //  ParameterizedType 表示参数化类型,带有类型参数的类型,即常说的泛型,如:List<T>、Map<Integer, String>、List<? extends Number>。
                val parameterizedType = javaClass.genericSuperclass as ParameterizedType
                val clazz = parameterizedType.actualTypeArguments[0] as Class<*>
                //通过反射加载类的inflate方法
                val declaredMethod = clazz.getDeclaredMethod("inflate", LayoutInflater::class.java,ViewGroup::class.java,Boolean::class.java)
                //通过调用对应方法并强转成T
                viewBinding = declaredMethod.invoke(null, inflater,container,false) as T
            } catch (e: NoSuchMethodException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            } catch (e: InvocationTargetException) {
                e.printStackTrace()
            }
            return viewBinding.root
        }
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            initCreateView(savedInstanceState)
        }
    
    }
    

    案例:

    class TestActivity : BaseActivity<ActivityTestBinding>() {
        override fun initCreate() {
            viewBinding.tvContent.setOnClickListener {
                  Toast.makeText(this@TestActivity,"${viewBinding.tvContent.text}",Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    class TestFragment : BaseFragment<FragmentTestBinding>() {
        private var param1: String? = null
        private var param2: String? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            arguments?.let {
                param1 = it.getString(ARG_PARAM1)
                param2 = it.getString(ARG_PARAM2)
            }
        }
        companion object {
    
            @JvmStatic
            fun newInstance(param1: String, param2: String) =
                TestFragment().apply {
                    arguments = Bundle().apply {
                        putString(ARG_PARAM1, param1)
                        putString(ARG_PARAM2, param2)
                    }
                }
        }
    
        override fun initCreateView(savedInstanceState: Bundle?) {
            viewBinding.tvTest.setOnClickListener {
                  Toast.makeText(activity,"${viewBinding.tvTest.text}",Toast.LENGTH_SHORT).show()
            }
        }
    }
    

    这样看是不是简化好多

    相关文章

      网友评论

          本文标题:ViewBinding

          本文链接:https://www.haomeiwen.com/subject/yydlgltx.html