我的问题是缓存导致的,
文件->清除缓存->清楚并重启
头一次用,我也不知道为什么是缓存问题。
官方文档链接:https://developer.android.com/topic/libraries/view-binding?hl=zh-cn
官方博客链接:https://medium.com/androiddevelopers/use-view-binding-to-replace-findviewbyid-c83942471fc
但是有网络要求
配置binding,类似插件?
首先,在build.gradle.kts中声明"插件"
android{
...
buildFeatures {viewBinding= true}
}
使用
忽略
某个布局文件不想用它,把tools:viewBindingIgnore="true" 属性添加到该布局文件的根视图中:
<LinearLayout
tools:viewBindingIgnore="true" >
</LinearLayout>
全局和非全局
非全局
然后用,在activity文件中,使用
class FirstActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
// val button1: Button = findViewById(R.id.button1)
val binding1 = FirstLayoutBinding.inflate(layoutInflater)
binding1.button1.setOnClickListener {
Toast.makeText(this, "You click Button 1", Toast.LENGTH_LONG).show()
}
// setContentView(R.layout.first_layout)
setContentView(binding.root)
}
}
首先命名规则,如layout文件为first_layout,采用驼峰命名法,FirstLayout+Binding
在onCreate()中输入FirstLayoutBinding,as自动提示导入包
import com.example.activitytest.databinding.FirstLayoutBinding
这里没提示那就八成出错了,我是清理缓存
然后这个,不懂就这这来:FirstLayoutBinding.inflate(layoutInflater)
最后,也不用改就这么来:setContentView(binding.root)
全局
看着有点?反复初始化?kotlin语言决定
那就回退findViewById()也还能用
class FirstActivity : AppCompatActivity() {
private lateinit var binding2: SecondLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
binding2 = SecondLayoutBinding.inflate(layoutInflater)
binding2.button2.setOnClickListener {}
setContentView(binding2.root)
}
fun func2(){
binding2 = SecondLayoutBinding.inflate(layoutInflater)
}
fun func3(){
val button1:Button=findViewById(R.id.button1);
}
}
1
1
1
1
1
1
1
1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现