Get Button Coordinates and Detect If Finger Is Over Them - Android

Get button coordinates and detect if finger is over them - Android

package com.example.touch;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

Button b1, b2, b3, b4;

int b1x1, b1x2, b1y1, b1y2;

private TextView xcordview;
private TextView ycordview;
private TextView buttonIndicator;
private RelativeLayout touchview;
private static int defaultStates[];
private Button mLastButton;
private final static int[] STATE_PRESSED = {
android.R.attr.state_pressed,
android.R.attr.state_focused
| android.R.attr.state_enabled };

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xcordview = (TextView) findViewById(R.id.textView4);
ycordview = (TextView) findViewById(R.id.textView3);
buttonIndicator = (TextView) findViewById(R.id.button_indicator);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);

b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
defaultStates = b1.getBackground().getState();

}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();

touchview.setOnTouchListener(new View.OnTouchListener() {

private boolean isInside = false;

@Override
public boolean onTouch(View v, MotionEvent event) {

int x = (int) event.getX();
int y = (int) event.getY();

xcordview.setText(String.valueOf(x));
ycordview.setText(String.valueOf(y));

for (int i = 0; i < touchview.getChildCount(); i++) {
View current = touchview.getChildAt(i);
if (current instanceof Button) {
Button b = (Button) current;

if (!isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(defaultStates);
}

if (isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(STATE_PRESSED);
if (b != mLastButton) {
mLastButton = b;
buttonIndicator.setText(mLastButton.getText());
}
}

}
}
return true;
}

});

}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
}

static boolean isPointWithin(int x, int y, int x1, int x2, int y1, int y2) {
return (x <= x2 && x >= x1 && y <= y2 && y >= y1);
}
}

layout file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="Y Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="X Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_toRightOf="@+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView"
android:layout_marginBottom="10dp"
android:layout_toRightOf="@+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="B1"
android:textColor="#000000" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:text="B2"
android:textColor="#000000" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button2"
android:text="B3"
android:textColor="#000000" />

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button3"
android:text="B4"
android:textColor="#000000" />

<TextView
android:id="@+id/button_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView4"
android:layout_marginRight="33dp"
android:text="No one"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button_indicator"
android:layout_alignBottom="@+id/button_indicator"
android:layout_marginRight="29dp"
android:layout_toLeftOf="@+id/button_indicator"
android:text="Entered: "
android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Detect which view your finger is sliding over in Android

The simple answer is you can't - not like the iPhone when in accessibility mode.

Until Ice Cream Sandwich that is. It now has the iPhone-like capability of being able to identify elements under your finger without having to lift it.

How to detect if finger already over the button on start new Activity

The task is solved using FragmentActivity.

On Touch Listener does not release button when finger is moved Android

You have to focus on RelativeLayout.

MyActivity.java

public class MyActivity extends Activity {

private RelativeLayout mainLayout;
private TextView myTag;
private TextView xcordview;
private TextView ycordview;

private MediaPlayer mp1;
private String currentTag;
private boolean areaDetected;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
myTag = (TextView) findViewById(R.id.tag);
xcordview = (TextView) findViewById(R.id.x_view);
ycordview = (TextView) findViewById(R.id.y_view);
currentTag = "";
initEvent();
}

private void initEvent() {
mainLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

int x = (int) motionEvent.getX();
int y = (int) motionEvent.getY();

xcordview.setText("X : " + String.valueOf(x));
ycordview.setText("Y : " + String.valueOf(y));

areaDetected = false;
for (int i = 0; i < mainLayout.getChildCount(); i++) {
View currentButton = mainLayout.getChildAt(i);
if (currentButton instanceof Button) {
Button b = (Button) currentButton;
String tag = b.getTag().toString();

if (!pointInside(x, y, b.getLeft(), b.getRight(), b.getTop(), b.getBottom())) {
b.setText("");
// b.setBackgroundResource(getResources().getColor(android.R.color.black));
} else {
areaDetected = true;
if (!currentTag.equals(tag)) {
currentTag = tag;
stopPlaying();
b.setText(tag);
mp1 = getMediaPlayer(tag);
mp1.start();
// b.setBackgroundResource(getResources().getColor(android.R.color.white));
}
}
}
}
if (!areaDetected) {
currentTag = "";
stopPlaying();
}
myTag.setText("Current tag : " + currentTag);
return true;
}
});
}

private void stopPlaying() {
if (mp1 != null) {
mp1.stop();
mp1.release();
mp1 = null;
}
}

private MediaPlayer getMediaPlayer(String tag) {
if (tag.equals("b1")) {
return MediaPlayer.create(MyActivity.this, R.raw.coffee_and_snow);
}
return MediaPlayer.create(MyActivity.this, R.raw.coffee_and_snow2);
}

static boolean pointInside(int x, int y, int x1, int x2, int y1, int y2) {
return (x <= x2 && x >= x1 && y <= y2 && y >= y1);
}
}

and the xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MyActivity">

<com.example.antoine.touchtest.MyButton
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="b1" />

<com.example.antoine.touchtest.MyButton
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/b1"
android:tag="b2" />

<com.example.antoine.touchtest.MyButton
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/b2"
android:tag="b3" />

<com.example.antoine.touchtest.MyButton
android:id="@+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/b3"
android:tag="b4" />

<TextView
android:id="@+id/x_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/y_view"
android:text="X : " />

<TextView
android:id="@+id/tag"
android:layout_above="@+id/x_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current tag : " />

<TextView
android:id="@+id/y_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Y : " />
</RelativeLayout>

Finally my custom button

MyButton

public class MyButton extends Button {

public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public MyButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
// return super.onTouchEvent(event);
return false;
}

}

A big thanks to this post ==> Get button coordinates and detect if finger is over them - Android

How do you detect when the user drags their finger over a specific object

I have solved this issue and created my own system of hitboxes. Here is my function for it. The function should be called repeatedly every moment you want to check for the collisions, or loop the function and just call it once at the start of the code. However, there is still one unsolved issue. I still can't figure out how to detect the color of that tile and run specific functions based on that color(which can change). And I might need 91 duplicates of this function since I have 91 tiles that need these hitboxes. Here is what I came up with anyways:

private fun collideDetect2() {
val warningColor = "#FF8C00" // part of a testing tool to help test my hardcoded hitboxes
val fixColor = "#00ED8E"

val playerX = player.x
val playerY = player.y
val tileX = tile69.x // tile69 is one of the objects I need to detect collision for on the grid of squares
val tileY = tile69.y
if (playerX <= (tileX + 155f)) {
if(playerX >= (tileX - 85f)) {
println("X collision detected.") //helped with debugging and testing
println("player's X is $playerX and tile's X is $tileX") //helped with debugging and testing
if (playerY >= (tileY + 75f)) {
if(playerY <= (tileY + 275f)) {
println("Y collision detected.")
println("player's Y is $playerY and tile's Y is $tileY")
if (!activated) { // activated was defined at the top of the file, "var activated = false" This variable allows the function to only run once when the collision is detected until the objects are no longer overlapping, instead of running every moment they are overlapping while it is being checked
activated = true
highlightRandomTiles() // the function I want it to run when the collision is detected for this specific tile
when ((1..2).random()) { // testing tool to tell me when the player image has overlapped. without the "activated" variable, it would tell me every single moment the hitbox was overlapping
2 -> {
tile69.setBackgroundColor(warningColor.toColorInt())
}
1 -> {
tile69.setBackgroundColor(fixColor.toColorInt())
}

}
}
}
else {
activated = false // allows the code to know the player has left the hitbox so the function will run again next time the collision occurs. Might not need this in all 4 places tho...
}
}
else {
activated = false
}
}
else {
activated = false
}
}
else {
activated = false
}
}

How to get the Touch position in android?

@Override
public boolean onTouchEvent(MotionEvent event)
{
int x = (int)event.getX();
int y = (int)event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
}

return false;
}

The three cases are so that you can react to different types of events, in this example tapping or dragging or lifting the finger again.



Related Topics



Leave a reply



Submit