问题描述
我有一个布局(如板)这样的包含细胞(按钮)
I have a layout(like board) like this that contains cells(buttons)
| A | B | C | D |
-----------------
| E | F | G | H |
-----------------
| I | J | K | L |
-----------------
| X | Y | Z | W |
我编程加入细胞,它们包含字母I设置。
I'm adding Cells programmatically, they contains letters I set.
public void addCells(String letters){
removeAllViews();
int let = 0;
for (int j = 0; j < 4; j++){
for (int i = 0; i < 4; i++){
String currentLetter = ""+letters.charAt(let);
//Cell object that contains it's position and letter.
Cell cell_ = new Cell(this.getContext(), new Point(i , j), new Letter(currentLetter));
this.addView(cell_);
this.cells[i][j] = cell_;
let++;
}
}
}
我的目标是通过手指移动这样的连接细胞:
My aim is connecting cells by finger moving like this:
我要回真正
从 onTouchEvent()
这样我就可以捕获所有沾上的ViewGroup中的 onInterceptTouchEvent()
I'm returning true
from onTouchEvent()
so I can capture all touchs in ViewGroup onInterceptTouchEvent()
public boolean onTouchEvent(MotionEvent motionEvent) {
return true;
}
但我无法得到的逻辑。我如何可以通过点击/触摸访问的某些子对象在一个ViewGroup?
But I couldn't get the logic. How can I access a certain child object by click/touch in that ViewGroup?
当我点击'A'的信,我想访问该单元对象。
When I click to 'A' letter, I want to access that cell object.
推荐答案
在一般:
-
父视图拦截所有触摸事件(X,Y)
The parent view intercepts all touch events (x,y)
onInterceptTouchEvent() { return true; }
在触摸事件,父找到匹配的活动地点,内观
On touch event, the parent finds the inner view that match the event location
onTouchEvent() { // see below }
如何父母能找到内心的看法?
您可以做到这一点在2种方式,
You can do it in 2 ways,
1)具有用于保存到细胞中的观点的参考板的数据结构([] [])。那么你知道什么是触摸事件的X,Y因此,如果所有的细胞都是平等的基础上,细胞大小和位置的简单计算出正确的电池。
1) Have a data structure ([][]) for the board that holds a reference to the cells views. Then you know what is the touch event X,Y so if all cells are equal simply calculate the correct cell based on the cells size and location.
View[][] board;
// Add the Views to the board in creation loop
int cellWidth = board[0][0].getMeasuredWidth();
int cellHeight = board[0][0].getMeasuredHeight();
int tragetX = (int)(x / cellWidth);
int targetY = (int)(y / cellHeight);
View targetCell = board[targetX][targetY];
// Do something with targetCell
2)遍历所有的单亲家庭子女(最后一个是最好的),并计算父位置内,与它的大小组合子视图位置确定如果发现孩子是目标或没有。
2) Iterate on all the parent children (last to first is best), and calculate the child view location inside the parent location and with combination of it's size determine if that child is the target or not.
View targetChild = null;
int[] loc = new int[2];
for (int i = getChildCount()-1; i >= 0; i--) {
View child = getChildAt(i);
child.getLocationInWindow(loc);
if (x >= loc[0] && x <= loc[0]+child.getMeasuredWidth() &&
y >= loc[1] && y <= loc[1]+child.getMeasuredHeight()) {
targetChild = child;
break;
}
}
// Do something with targetChild
以上是一个例子,请写出更好的code :)(重用禄,等...)
The above is an example, please write a better code :) (reuse loc, etc...)
这篇关于Android的onInterceptTouchEvent,拿在童车的ViewGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!