在Activity 和 Fragment 只要操作 xml 的元件,在 onCreate 時就要先加一堆
元件宣告( findViewById )再來操作, 使用 View Binding,大部份就可以
不用 findViewById,直接用元件的 id 名稱就可以了,是不是很方便呀。
在build.gradle(app) 中宣告
android {
...
buildFeatures {
viewBinding true
}
}
在activity 中使用 ViewBinding
class Day18Activity : AppCompatActivity() {
private lateinit var viewModel: Day18ViewModel
// ViewBinding
private lateinit var binding: ActivityDay18Binding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_day18)
// ViewBinding
binding = ActivityDay18Binding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//var dayTitle: TextView = findViewById(R.id.tvtitle)
viewModel = ViewModelProvider(this).get(Day18ViewModel::class.java)
viewModel.mTitle.observe(this){
//dayTitle.text = it
// ViewBinding use id name
binding.tvtitle.text = it
}
viewModel.load()
}
}
在fragment 中使用 ViewBinding
//class Day16Fragment : Fragment(R.layout.day16_fragment) {
class Day16Fragment : Fragment() {
//ViewBinding
private var _binding: Day16FragmentBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = Day16FragmentBinding.inflate(inflater,container,false)
val view = binding.root
return view //super.onCreateView(inflater, container, savedInstanceState)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
val model: Day16ViewModel by activityViewModels()
//var textView:TextView = this.requireView().findViewById(R.id.fragmenttext)
//textView.text = model.getArticleTitle()
//ViewBinding use id
binding.fragmenttext.text = model.getArticleTitle()
println("Fragment call ViewModel get Acticle Title = "+model.getArticleTitle())
}
}
與 findViewById 的區別
Null safety 空安全:由於視圖綁定創建了對視圖的直接引用,因此不存在因視圖 ID
無效而導致空指針異常的風險。
Type safety 類型安全:每個綁定類中的字段的類型與其在 XML 文件中引用的視圖相匹配。
https://developer.android.com/topic/libraries/view-binding