I have multiple buttons in my LinearLayout on my activity_main, and want to detect which Button is closest to the users finger. When the users moves his finger in a single gesture the closest button should highlight and when he removes his finger the closest button should do its onClick function.
It should act like the default keyboard on android or the iphone calculator. It selects the button closest to the finger. When you drag your finger across it will change the selection to the closest key and only when you release your finger does it do the onClick function.
Referencing Get button coordinates and detect if finger is over them - Android I got to the point where selection works, but only if I tap anywhere that isn't a button and it doesn't work to select closest button when not over a button.
(Programming for API 21 in case thats important)
activity_main.xml
<TextView/>
<ButtonLayout>
<LinearLayout1>
<Button1/>
<Space/>
<Button2/>
<Space/>
<Button3/>
<Space/>
<Button4/>
</LinearLayout1>
<LinearLayout2>
<Button5/>
<Space/>
<Button6/>
<Space/>
<Button7/>
<Space/>
<Button8/>
</LinearLayout2>
</OuterLinearLayout>
Java
private View.OnTouchListener buttonLayoutTouchListener= new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
//OuterLayout
for (int i = 0; i < buttonLayout.getChildCount(); i++) {
View inner = buttonLayout.getChildAt(i);
//Inner
if(inner instanceof LinearLayout) {
for (int j = 0;j<((LinearLayout) inner).getChildCount();j++) {
View current = ((LinearLayout) inner).getChildAt(j);
if (current instanceof Button) {
Button b = (Button) current;
Rect rect = new Rect();
b.getGlobalVisibleRect(rect);
//factors for textview
rect.top-=300;
rect.bottom-=300;
if (!isPointWithin(x, y, rect.left, rect.right, rect.top,
rect.bottom)) {
b.getBackground().setState(defaultStates);
}
if (isPointWithin(x, y, rect.left, rect.right, rect.top,
rect.bottom)) {
if (b != mLastButton) {
mLastButton = b;
b.getBackground().setState(STATE_PRESSED);
//highlight button finger currently over
Log.d("button",mLastButton.getText().toString());
}
}
}
}
}
}
return true;
}
};
static boolean isPointWithin(int x, int y, int x1, int x2, int y1, int y2) {
return (x <= x2 && x >= x1 && y <= y2 && y >= y1);
}