V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hu8245
V2EX  ›  Android

请教大佬们 ViewBinding 和 findViewById 的差异

  •  
  •   hu8245 · 2022-03-21 23:43:10 +08:00 · 4342 次点击
    这是一个创建于 738 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Android 新手。在实现一个功能,简单来说,就是一个 静音按钮,是一个 ImageView ,点击静音按钮,无色的 icon_passive 变为 icon_active 。 我一开始用 ViewBinding ,发现,点击后,红色的 icon_active 是叠加在 icon_passive 之上的。但是 findViewById 就是替换的效果,不会叠加。想问各位大佬,ViewBinding 和 findViewById 有使用上的区别吗?在 Google/StackOverFlow 找不到理想的回答。

    protected void initButtonAndEvents(){
    
      // ImageView muteAudio = binding.ivMuteAudio; // 会出现 图像 叠加
      ImageView muteAudio = getActivity().findViewById(R.id.iv_mute_audio);    // 不会出现图像叠加       	   muteAudio.setImageDrawable(getResources().getDrawable(R.drawable.ic_mute_audio_default, null));
      muteAudio.setOnClickListener(v -> {
    
                mViewModel.setIsMuteAudio(!mViewModel.getIsMuteAudio());
                muteAudio.setImageDrawable(getResources().getDrawable(mViewModel.getIsMuteAudio() ? R.drawable.ic_mute_audio_active : R.drawable.ic_mute_audio_default, null));
            });
    }
    
    7 条回复    2022-03-25 11:33:35 +08:00
    Tolcol
        1
    Tolcol  
       2022-03-21 23:53:57 +08:00   ❤️ 1
    可以看看 setContentView 那边,可能 ViewBinding 设置了两次?
    hu8245
        2
    hu8245  
    OP
       2022-03-22 00:15:11 +08:00
    @Tolcol 多谢。问题不在这里,这两个获得的 view 对象是同一个。根本原因在其他地方(后来发现切换横屏导致了这段代码执行了两次。)。thread 结束
    251
        3
    251  
       2022-03-22 00:16:36 +08:00
    直接学 compose API 吧。
    hfl1995
        4
    hfl1995  
       2022-03-22 00:25:49 +08:00 via iPhone
    你直接 binding.ivmute.setxxx 这样调用呢
    debuggeeker
        5
    debuggeeker  
       2022-03-22 09:03:28 +08:00
    在编译文件中找到布局名字 ViewBinding 的 class 这个类,看看里面的逻辑你就会明白了。
    先说结论,我看过。生成的 xxxxViewBinding 这个类的代码做的事情,就是 findViewById 。
    iovekkk
        6
    iovekkk  
       2022-03-22 09:31:50 +08:00
    既然使用 viewbinding 了,点击事件就设置在 xml 文件中吧
    android:onClick="@{() -> click.onclick()}"
    在 activity 中,创建一个 click 类,写一个成员方法即可
    tuimaochang
        7
    tuimaochang  
       2022-03-25 11:33:35 +08:00
    以前 kotlin 还能用 kotlin-android-extensions 来实现直接用 xml 里的 id ,后来升级这玩意就废了……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2914 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:30 · PVG 08:30 · LAX 17:30 · JFK 20:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.