You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中实现含RecyclerView的TabLayout+ViewPager2?报错求助

问题1:安装失败提示 Unknown failure: cmd: Can't find service: package 解决方案
  • 重启ADB服务:打开终端依次执行以下命令
    adb kill-server
    adb start-server
    
  • 检查设备连接:重新插拔USB线,确认设备已开启开发者模式和USB调试,并将USB连接模式切换为「文件传输」
  • 清理Android Studio缓存:依次点击 File → Invalidate Caches...,勾选「Clear file system cache and local history」后点击「Invalidate and Restart」
  • 重置USB调试授权:在设备的开发者选项中找到「撤销USB调试授权」,重新连接设备并授权电脑访问
  • 更换硬件:尝试换一个USB端口或数据线,排除硬件故障
问题2:NullPointerException(findViewById(R.id.extra) 不能为空)解决方案
  • 核查布局文件:确认对应布局(activity_main.xml 或 Fragment 布局)中存在 android:id="@+id/extra" 的控件,ID拼写完全一致(注意大小写、下划线)
  • 确保布局加载时机:
    • 在MainActivity中,必须在setContentView(R.layout.activity_main)之后调用findViewById
    • 在Fragment中,需在onViewCreated或onCreateView加载完成视图后,使用view.findViewById(R.id.extra)查找控件,禁止在onCreate阶段调用
  • 修正ViewPager2 Fragment的控件查找逻辑:如果extra是Fragment内的控件,不要用getActivity().findViewById跨上下文查找,必须基于当前Fragment的视图对象查找
  • 替换为ViewBinding(推荐):在模块的build.gradle中启用ViewBinding,通过绑定对象直接访问控件,避免ID拼写错误和空指针:
    android {
        ...
        buildFeatures {
            viewBinding true
        }
    }
    
    在Activity中使用:
    private lateinit var binding: ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 直接通过binding访问控件
        binding.extra.doSomething()
    }
    

内容的提问来源于stack exchange,提问作者Vivek Jaiswal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:06:05