【问题标题】:How to define a large group of imageViews?如何定义一大组 imageViews?
【发布时间】:2018-05-20 09:48:34
【问题描述】:

我在 android studio 中有 64 个图像视图,我不想像这样一一定义它们:

ImageView iv11 = findViewById(R.id.iv11);

ImageViews 的 id 以 iv11 开头(第一个数字是 row 和第二个 col)并以 iv88 结尾有没有办法将它们一起定义?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    通过 for 循环构造您的 ImageView id 并调用 getResources().getIdentifier()

    for (int col = 0 ; col < 8; ++col) {
        for (int row = 0 ; row < 8; ++row) {
            String idStr = "iv" + String.valueOf(row) + String.valueOf(col);
            @IdRes int id = context.getResources().getIdentifier(idStr, "id", context.getPackageName());
    
            ImageView imgView = findViewById(id);
            // Do something with your image
        }
    }
    

    不管怎样,屏幕上有那么多ImageView,它应该由像ListView、RecyclerView这样的适配器管理...

    【讨论】:

      【解决方案2】:

      您应该使用adapter 填充您的视图。由于听起来您需要将图像显示在网格中,因此您可以将GridView 与适配器一起使用。

      有很多教程可以指导您执行此操作;例如:您可以先查看this。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多