【发布时间】:2018-05-20 09:48:34
【问题描述】:
我在 android studio 中有 64 个图像视图,我不想像这样一一定义它们:
ImageView iv11 = findViewById(R.id.iv11);
ImageViews 的 id 以 iv11 开头(第一个数字是 row 和第二个 col)并以 iv88 结尾有没有办法将它们一起定义?
【问题讨论】:
我在 android studio 中有 64 个图像视图,我不想像这样一一定义它们:
ImageView iv11 = findViewById(R.id.iv11);
ImageViews 的 id 以 iv11 开头(第一个数字是 row 和第二个 col)并以 iv88 结尾有没有办法将它们一起定义?
【问题讨论】:
通过 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这样的适配器管理...
【讨论】: