按钮阵列上的ANDROID onTouchListener



我在一个按钮数组中放了很多按钮(16*16)。按钮编号与它们应该在另一个数组中进行的更改直接相关(例如,button[12][7]stat[12][7]的值设置为1)

所以我认为可以在onTouch方法中放一行,对每个按钮做出反应。示例(当然,不起作用)

public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
if(arg0 == button[int a][int b]){stat[a][b]=1};

在这个伪代码中,按钮将创建2个ints,用于描述传递给stat数组的数组的2个维度。

如果有人能解决这个问题,他今晚会为我节省几个小时。

谢谢你的回答。

我认为HasMap是更好的解决方案

private HashMap<Integer,Button> btnMap = new HashMap<Integer, Button>();
private void init(){
    Button yourFirstBtn = (Button) findViewById(R.id.yourFirstBtn);
    btnMap.put(yourFirstBtn.getId(), yourFirstBtn);
    for(Button tempBtn: btnMap.values()){
        tempBtn.setOnClickListener(this);
    }
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
    Button clickedBtn = btnMap.get(v.getId());
}

是否将onTouchListener添加到按钮的容器中?

最好的办法是为每个按钮添加一个onTouchListener,然后arg0将对应于特定的按钮。

另一种选择是使用GridView,它有一个可以使用的setOnItemClickListener。http://developer.android.com/reference/android/widget/GridView.html

将每个按钮添加到数组时,设置一个指示其索引的标记。标记用于将特性添加到视图中,而不必使用其他数据结构。

例如:

button[12][7].setTag("12|7");

如果你的按钮是用XML预定义的,你可以用做同样的事情

android:tag="12|7"

然后在触摸监听器中(我假设所有按钮都连接了同一个),从被触摸的视图中获取标签:

String tag = (String) view.getTag();

然后进行子字符串输出,并根据需要使用两个索引:

String indx1 = tag.substring(0, tag.indexOf("|"));
String indx2 = tag.substring(tag.indexOf("|")+1);
stat[Integer.parseInt(indx1)][Integer.parseInt(indx2)] = 1;

试试这样的东西:

Button[][] myButtonMatrix = new Button[] {
 new Button[] { button11, button12, button13, button 14 },
 new Button[] { button21, button22, button23, button24 }
};
public class MatrixButtonListener implements View.OnClickListener {
        private int x;
        private int y;
        public MatrixButtonListener(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int getX() { return x; }
        public int getY() { return y; }
        @Override
        public void onClick(View v) {
            stat[x][y] = x-y; // changes were made only in relation to x and y, nothing else
            // for example:
            if(x == 0) { 
                // button in first row
                // do something
            }
        }
    };
// to apply to each button in matrix:
for(int i=0; i<myButtonMatrix.length; i++) {
    for(int j=0; j<myButtonMatrix[i].length; j++) {
         myButtonMatrix[i][j].setOnClickListener(new MatrixButtonListener(i,j));
    }
}

这应该做什么:

创建一个通用的OnClickListener类,该类将x和y位置作为参数,因此每个OnClickListener都有相同的行为,但x和y的位置不同,具体取决于按钮本身。

注:此项未经测试。

编辑:

另一种方法是使用自定义按钮类,该类还包含X/Y坐标。只需将onClickListener添加到每个按钮,将其投射回您的自定义视图,然后请求x/y。

最新更新