Kotlin - 1. View Binding

1、View Binding

一、Enabling View Binding

 1 android {
 2 
 3     // module级别的build.gradle文件中添加下名的配置
 4     // 会自动为xml文件生成binding class
 5     // 命名规则是Pascal case  + Binding
 6     // 可在XML中添加属性来屏蔽生成binding class
 7     // tools:viewBindingIgnore="true"
 8     buildFeatures {
 9         viewBinding true
10     }
11 }

 

二、Using View Binding in Activities

 1 class MainActivity : AppCompatActivity() {
 2 
 3     private lateinit var binding: ActivityMainBinding
 4 
 5     override fun onCreate(savedInstanceState: Bundle) {
 6         super.onCreate(savedInstanceState)
 7         binding = ActivityMainBinding.inflate(layoutInflater)
 8         val view = binding.root
 9         setContentView(view)
10        
11         // ...
12 
13     }
14 }
15 
16 
17 binding.myButton.setOnClickListener { // Button Tapped }
18 binding.myTextView.text = "View Binding is the best!"

 

三、Using View Binding in Fragments

inflate methos

 1 class DemoInflateFragment : Fragment() {
 2 
 3     private var fragmentDemoBinding: FragmentDemoBinding = null
 4 
 5     // 注意是在onCreateView中inflate内容,所以AsyncLayoutInflater不适应Fragment
 6     override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View {
 7         val binding = FragmentDemoBinding.inflate(inflater, container, false)
 8         fragmentDemoBinding = binding
 9 
10         binding.myButton.setOnClickListener {
11              // Button Tapped
12         }
13    
14         binding.myTextView.text = "View Binding is the best!"
15 
16         return binding.root
17     }
18     override fun onDestroyView() {
19         // View不见时Fragment可以存在
20         fragmentDemoBinding = null
21         super.onDestroyView()
22     }  
23 }

 

posted @ 2021-12-07 11:37  大大章鱼  阅读(208)  评论(0编辑  收藏  举报