首页 > 解决方案 > 获取 2D ImageButton ArrayList 的位置

问题描述

我有一个名为ArrayList<ArrayList<ImageButton>> boardImageButtons.

在该方法onClick(View view)中,我将单击的图像按钮命名为 ((ImageButton) view) btn

我想获得该对象在 2D ArrayList 中的位置( i& )。j

我尽量避免运行 throw 所有 2D ArrayList,比较对象并获取 equals 对象的i& j

你有更好的建议吗?

有什么方法可以传递额外的变量onClick(View view)吗?

标签: javaandroidimagebutton

解决方案


在您的应用程序开始时创建一个HashMap

class Pair {
    int x, y;
    Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}


Map<ImageButton, Pair> map = new HashMap<?>();

通过使用一些循环或您的逻辑放置所有值来初始化地图

map.put(btn1, new Pair(1, 2));
..
..

在检索位置时,使用

Pair myPair = map.get(view);

推荐阅读