LiiYuan

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

我的问题是缓存导致的,
文件->清除缓存->清楚并重启


头一次用,我也不知道为什么是缓存问题。

官方文档链接: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

posted on   李ly  阅读(187)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
 
点击右上角即可分享
微信分享提示