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

Android Studio中如何初始化TextView数组并循环获取视图?

循环获取多个TextView视图的解决方案

方法一:通过资源名称动态获取ID

利用getResources().getIdentifier()方法,将拼接好的视图名称转换成对应资源ID,实现循环获取:

TextView[] textViews = new TextView[7];
for (int i = 0; i <= 6; i++) {
    // 拼接TextView的ID名称
    String viewIdStr = "textview" + i;
    // 获取对应资源ID:参数分别为ID名称、资源类型(这里是id)、包名
    int viewId = getResources().getIdentifier(viewIdStr, "id", getPackageName());
    // 绑定视图到数组
    textViews[i] = findViewById(viewId);
}

注意:如果开启代码混淆,需在混淆规则中保留这些TextView的ID名称,避免被混淆导致无法找到资源。

方法二:遍历父容器的子视图

如果这些TextView都处于同一个布局容器(如LinearLayout、ConstraintLayout)中,可直接遍历容器子视图,筛选出TextView类型的视图:

// 先获取父容器
LinearLayout textContainer = findViewById(R.id.text_container);
TextView[] textViews = new TextView[7];
int count = 0;

for (int i = 0; i < textContainer.getChildCount(); i++) {
    View childView = textContainer.getChildAt(i);
    if (childView instanceof TextView && count < 7) {
        textViews[count++] = (TextView) childView;
    }
}

这种方式不依赖视图ID名称,不受混淆影响,但需确保父容器中目标TextView的顺序和数量符合预期。

方法三:使用ViewBinding(推荐)

如果项目已启用ViewBinding,可直接通过自动生成的Binding对象获取所有视图,类型安全且无需手动findViewById:

// 假设布局文件为activity_main.xml,生成的Binding类为ActivityMainBinding
ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());

// 直接将视图存入数组
TextView[] textViews = new TextView[]{
    binding.textview0,
    binding.textview1,
    binding.textview2,
    binding.textview3,
    binding.textview4,
    binding.textview5,
    binding.textview6
};

ViewBinding是Android官方推荐的视图绑定方式,编译时会检查视图ID是否存在,避免运行时异常。

内容的提问来源于stack exchange,提问作者Hamza Ateya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:15:39