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

Android View Binding中无法找到getGridView()方法,如何访问GridView?

解决View Binding访问GridView的问题

你遇到的问题是因为View Binding在Java中的访问规则和你参考的示例存在差异:

  • 对于XML中id为grid_view的控件,生成的Binding类会直接生成驼峰式命名的public字段,而非getter方法。
  • 你不需要调用getGridView(),直接通过binding.gridView即可访问该GridView。

修改后的代码如下:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    
    GridView grid = binding.gridView; // 直接访问字段
}

补充说明:

  • View Binding生成的Binding类中,所有带id的控件都会被转为驼峰式的public成员变量,无需通过getter/setter方法访问。
  • 你参考的示例里的getName()写法,要么是View Binding早期版本的用法,要么是Data Binding的写法(Data Binding会生成getter方法),而View Binding简化了访问逻辑,直接通过字段即可操作控件。

内容的提问来源于stack exchange,提问作者Real Noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:45:35