今天学习《第一行代码》时使用ViewBinding代替findViewById(),发现代替以后button无法激活intent,从https://www.jianshu.com/p/86f780f3aabd 找到了问题所在
问题代码
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(tag,"onCreate")
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(R.layout.activity_main)
binding.startNormalActivity.setOnClickListener {
val intent = Intent(this, NormalActivity::class.java)
startActivity(intent)
}
binding.startDialogActivity.setOnClickListener {
val intent = Intent(this, DialogActivity::class.java)
startActivity(intent)
}
}
关键就是在setContentView(R.layout.activity_main)
这行代码出现了问题
tips:这行代码是自动生成的
修改
需要改为在setContentView()
前进行binding
绑定
val binding = ActivityMainBinding.inflate(layoutInflater)
然后setContentView
改为setContentView(binding.root)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(tag,"onCreate")
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
...
}
标签:val,setContentView,ViewBinding,button,binding,savedInstanceState,intent,按钮,onCre
From: https://www.cnblogs.com/y-ming/p/16746998.html