I have implemented the onGenericMotionEvent method in my activity as follows:
#Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_SCROLL:
float scrollX = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
float scrollY = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
Log.d("MA", "Mouse scrolled " + scrollX + ", " + scrollY);
return true;
}
}
return super.onGenericMotionEvent(event);
}
Although I roll the wheel button of the mouse, I never get the ACTION_SCROLL event, but only ACTION_HOVER_ENTER, ACTION_HOVER_MOVE and ACTION_HOVER_EXIT events.
The view over which I want to scroll is defined as follows:
<TextView android:id="#+id/Report"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="1dp"
android:visibility="visible"
android:clickable="true"
android:focusable="true"
style="#style/ReportStyle"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="vertical"
android:paddingLeft="#dimen/smallMargin_land"
android:paddingRight="#dimen/smallMargin_land"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/cmdRows"
app:layout_goneMarginTop="1dp"
/>
What is wrong in my implementation?
Related
I have a microphone button in my app with which user inputs voice. It is using an OnTouchListener to detect whether user holds down the button or not. If they hold the button but drag their finger outside the button, MotionEvent still considers action as "ACTION_DOWN", even if they touch near the edge of the screen, as long as they don't stop touching. We need to change that so if the user drags their finger off of the button then MotionEvent picks up as "ACTION_UP".
recordBtn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
//User stops touching the button.
case MotionEvent.ACTION_UP:
if(isRecording) {
stopRecording();
isRecording = false;
}
break;
//User touches the button.
case MotionEvent.ACTION_DOWN:
if(!isRecording) {
startRecording();
isRecording = true;
}
break;
}
return false;
}
});
XML:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.9">
<TextView
android:id="#+id/recordText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/custom_button"
android:layout_centerHorizontal="true"
android:layout_marginStart="8dp"
android:layout_marginTop="195dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:gravity="center"
android:fontFamily="sans-serif"
android:text="#string/hold_the_mic_and_record"
android:textColor="#color/white"
android:textSize="20sp"/>
<Button
android:id="#+id/custom_button"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:background="#drawable/microphone" />
</RelativeLayout>
I have created an application in which there is a button which moves on touching it .
Now for onTouch I have implemented A different class.There are 2 classes one is main CircleMActivity.java and another for onTouch.
Now the app is running fine but there is one problem. When I am clicking on the button and moving it It is moving but there is a gap between the button and the screen touch.
What I want is to move it exactly where I touch it NOT at some distance later OR you can think that I want to move it at exact the cursor position.
How should I achieve it ?
Code:
CircleMActivity.java:
public class CircleMActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circle_m);
Button b=(Button)findViewById(R.id.btn1);
MultiTouch mtb=new MultiTouch(this);
b.setOnTouchListener(mtb);
}
}
MultiTouch.java:
public class MultiTouch implements OnTouchListener{
float mPrevX,mPrevY;
CircleMActivity cm;
public MultiTouch(CircleMActivity circleMActivity) {
// TODO Auto-generated constructor stub
cm=circleMActivity;
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
float currentX,currentY;
int action=arg1.getAction();
switch(action){
case MotionEvent.ACTION_DOWN:
mPrevX = arg1.getX();
mPrevY = arg1.getY();
break;
case MotionEvent.ACTION_MOVE:
currentX = arg1.getRawX();
currentY = arg1.getRawY();
MarginLayoutParams marginParams = new MarginLayoutParams( arg0.getLayoutParams());
marginParams.setMargins((int)( currentX - mPrevX), (int)( currentY - mPrevY),0, 0);
LayoutParams layoutParams = new LinearLayout.LayoutParams(marginParams);
arg0.setLayoutParams(layoutParams);
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
activity_circle.xml:
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#000000"
android:weightSum="100">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="4.95"
android:background="#fff"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="X coord"
android:textColor="#ff00ee"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Y coord"
android:textColor="#ff00ee"
android:inputType="number" />
<EditText
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Radius"
android:textColor="#ff00ee"
android:inputType="number" />
<EditText
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textColor="#ff00ee"
android:hint="Colour"
android:inputType="number" />
</LinearLayout>
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.95"
android:background="#drawable/custom" />
"
</LinearLayout>
So how should I achieve it ?
It is a simple coordinates maths . In your
case MotionEvent.ACTION_DOWN:
mPrevX = arg1.getX();
mPrevY = arg1.getY();
break;
Make
mPrevY = arg1.getY()+250;
Well It will go out of the child linear layout but it is looking good !
I'm trying to get control buttons to pop on/off screen when the screen is tapped. They will overlay a video. The problem I'm running in to is how to create a touch event for a layout that has been inflated.
The routine is as follows: 1) set initial content to the video; 2) inflate layout(XML), that contains the controls, over the top of the video; 3)(NEED TO DO) create onTouch event for the newly inflated layout that hides/shows the buttons when the user taps the screen.
Layout containing the buttons to show/hide:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dpad_grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="3"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/tiltUp"
android:background="#drawable/arrow_up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_row="0"
android:layout_column="1"/>
<Button
android:id="#+id/panRight"
android:background="#drawable/arrow_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_row="1"
android:layout_column="2"/>
<Button
android:id="#+id/tiltDown"
android:background="#drawable/arrow_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="8dp"
android:layout_row="2"
android:layout_column="1"/>
<Button
android:id="#+id/panLeft"
android:background="#drawable/arrow_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_row="1"
android:layout_column="0"/>
</GridLayout>
<Button
android:id="#+id/zoomIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:background="#drawable/zoom_in"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"/>
<Button
android:id="#+id/zoomOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/zoom_out"
android:layout_marginRight="0dp"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/zoomIn"/>
<Button
android:id="#+id/irisDarker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="#drawable/iris_darker"/>
<Button
android:id="#+id/irisBrighter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/irisDarker"
android:background="#drawable/iris_brighter"/>
<Button
android:id="#+id/focusFar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/dpad_grid"
android:layout_marginRight="20dp"
android:layout_alignParentStart="true"
android:background="#drawable/focus_far"/>
<Button
android:id="#+id/focusNear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/focus_near"
android:layout_alignTop="#+id/focusFar"
android:layout_alignStart="#+id/irisBrighter"/>
<Button
android:id="#+id/snapshot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#drawable/camera"
android:layout_alignEnd="#+id/focusFar"
android:layout_alignParentStart="true"/>
<Button
android:id="#+id/settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#drawable/gear"/>
</RelativeLayout>
Code for adding the video and inflating the above layout:
#Override
public void onResume() {
super.onResume();
RelativeLayout.LayoutParams relativeLayoutParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
mv = new MjpegView(this);
setContentView(mv);
LayoutInflater inflater = getLayoutInflater();
getWindow().addContentView(inflater.inflate(R.layout.screen2, null), relativeLayoutParams);
Thanks for any help!
EDIT: here's what I'm currently working with. Why does my code not get into the touch event when I touch the screen?
LayoutInflater inflater = getLayoutInflater();
control_buttons = inflater.inflate(R.layout.screen2, null);
control_buttons.setOnTouchListener(new View.OnTouchListener() {
boolean gone = true;
#Override
public boolean onTouch(View v, MotionEvent event) {
System.out.println("In OnTouch");
if ( (event.getAction() == MotionEvent.ACTION_DOWN) && (gone == true) ){
getWindow().addContentView(control_buttons, relativeLayoutParams);
gone = false;
return true;
}
else if ((event.getAction() == MotionEvent.ACTION_DOWN) && (gone == false)) {
v.setVisibility(View.GONE);
gone = true;
return true;
}
return false;
}
});
This may work better for you. This will only work if the children in your RelativeLayout are either Buttons or GridLayouts that contain Buttons.
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.yourId);
relativeLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
for(int i = 0; i < relativeLayout.getChildCount(); i++) {
if(relativeLayout.getChildAt(i) instanceof Button) {
Button temp = (Button) relativeLayout.getChildAt(i);
if(temp.getVisibility() == View.INVISIBLE) {
temp.setVisibility(View.VISIBLE);
} else {
temp.setVisibility(View.INVISIBLE);
}
} else if(relativeLayout.getChildAt(i) instanceof GridLayout) {
GridLayout temp = (GridLayout) relativeLayout.getChildAt(i);
for(int g = 0; g < temp.getChildCount(); g++) {
Button tempButton = (Button) temp.getChildAt(g);
if(tempButton.getVisibility() == View.INVISIBLE) {
tempButton.setVisibility(View.VISIBLE);
} else {
temp.setVisibility(View.INVISIBLE);
}
}
}
}
}
return false;
}
});
So I have this animation I have been working on. Essentially, when you click the image all it does is simply animate the image to a new Y coordinate. Note: Keep in mind that my images are all scaled appropriately for mdli, hdpi, xhdpi etc. So I have 2 problems: 1. When I use .setY on an image view, the y coordinate is loaded differently on other phones. 2. When I use both my image and txt animate methods, they both animate to different y coordinates based on different phones/screens. So my question is how do I fix both of these problems so that they are consistent across all screen sizes?
public class MainActivity extends Activity {
final String tag = "My activity";
ImageView mWhatsTheAnswerImg, mInspireMeImg, mHelpMeThink, mTalkToVince;
ObjectAnimator mImageAnimation, mTxtAnimation;
TextView mWhatsTheAnswerText, mInspireMeTxt, mHelpMeThinkTxt, mTalkToVinceTxt;
boolean mWhatsTheAnswerBOOL, mInspireMeBOOL, mHelpMeThinkBOOL, mTalkToVinceBOOL =false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.hide();
mInspireMeImg = (ImageView) findViewById(R.id.inspireme);
mInspireMeImg.setY(750);
mInspireMeTxt = (TextView) findViewById(R.id.inspireMeTxt);
mInspireMeTxt.setY(750);
mInspireMeImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mInspireMeBOOL) {
imageAnimate(mInspireMeImg, 750);
txtAnimate(mInspireMeTxt, 750);
Log.w(tag, "DOWN Coordinates: " + mInspireMeImg.getY() + "Txt: " + mInspireMeTxt.getY());
mInspireMeBOOL = false;
} else {
mInspireMeBOOL = true;
imageAnimate(mInspireMeImg, +290);
txtAnimate(mInspireMeTxt, +290);
Log.w(tag, "UP Coordinates: " + mInspireMeImg.getY() + "Txt: " + mInspireMeTxt.getY());
}
}
});
Image animate and txt animate methods:
private void imageAnimate(ImageView img, float YCoordinates){
mImageAnimation =ObjectAnimator.ofFloat(img, View.TRANSLATION_Y,YCoordinates);
Log.w(tag, "IMG Coordinates: " + img.getY());
mImageAnimation.setDuration(1000);
mImageAnimation.start();
}
private void txtAnimate(TextView txt, float YCoordinates){
mTxtAnimation = ObjectAnimator.ofFloat(txt, View.TRANSLATION_Y, YCoordinates);
Log.w(tag, "TXT Coordinates: " + txt.getY());
mTxtAnimation.setDuration(1000);
mTxtAnimation.start();
}
}
Edit: XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.wyatt.avinceandroid.app.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/Background"
android:src="#drawable/coachvincebackground"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:id="#+id/inspireme"
android:src="#drawable/inspiremescreen"
android:scaleType="fitXY"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/inspireMeTxt"
android:layout_alignTop="#+id/helpMeThink"
android:layout_centerHorizontal="true"
android:layout_marginTop="89dp" />
<ImageView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:id="#+id/helpMeThink"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:src="#drawable/helpmethinkscreen"
android:scaleType="fitXY"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/helpMeThinkTxt"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:id="#+id/whatsTheAnswer"
android:src="#drawable/whatstheanswerscreen"
android:scaleType="fitXY"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/whatsTheAnswerTxt"
android:layout_alignTop="#+id/AskVince"
android:layout_alignLeft="#+id/inspireMeTxt"
android:layout_alignStart="#+id/inspireMeTxt" />
<ImageView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:id="#+id/AskVince"
android:src="#drawable/askvincescreen"
android:scaleType="fitXY"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/askVinceTxt"
android:layout_below="#+id/helpMeThinkTxt"
android:layout_centerHorizontal="true" />
</RelativeLayout>
The setY and other similar methods expect values in pixels. Now, this is exactly where the problem lies. Different phones have screens of different resolutions and so the 750th pixel will be located at different positions on different phones unless two displays are identical.
The solution is simple. Use values in DP:
mInspireMeImg.setY(dpToPx(750));
and keep this method stored somewhere:
public static int dpToPx(float dpValue, Context context){
return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
}
More about DP unit:
http://developer.android.com/training/multiscreen/screendensities.html
What is the difference between "px", "dp", "dip" and "sp" on Android?
I have 4 buttons in my android app activity. This is what it looks like:
As you can see, the textViews at the bottom of the screen display the x and y coordinates. The coordinates are in reference to a relative layout. (See below given code)
Now, what I want to do is get the x and y coordinates of the 4 buttons at runtime and then figure out if my finger is touching the buttons while moving or not. In simple words, I want to press the buttons by swiping my finger over them instead of lifting and touching. How can I achieve it? I want to implement it in my piano application.
I was able to get the coordinates on screen and they change as I move my finger.
So, my question is How can I get the coordinates of the buttons and detect if my finger is swiping above them?:
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:id="#+id/relativelayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Y Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="X Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView2"
android:layout_above="#+id/textView"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView3"
android:textColor="#000000"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView4"
android:textColor="#000000"
android:layout_marginBottom="10dp"
android:layout_above="#+id/textView"
android:layout_toRightOf="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:textColor="#000000"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button4"
android:textColor="#000000"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
Java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
RelativeLayout touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
});
}
}
Thank you all very very much!
Update:
public class MainActivity extends Activity {
RelativeLayout touchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
Button button = (Button) findViewById(R.id.button);
button.setBackgroundColor(Color.BLUE);
break;
}
}
return true;
}
});
}
private boolean checkInterSection(View view, float rawX, float rawY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
}
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>
private boolean checkInterSection(View view, int rawX, int raxY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.BLUE);// Type casting may not be required
}else{
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.WHITE);
}
break;
}
}
getX() getY() for a OnTouchListener give coordinates relative the the cooresponding view.
If you prefer screen coordinates instead you can use one of the following
overwrite onTouchEvent for the activity and remove OnTouchListener-s for buttons,
in which case MotionEvent will report screen coordinates instead of Button coordinates
#Override
public boolean onTouchEvent (MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
use getTop() getLeft() in OnTouchListener for a button:
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()+v.getLeft()));
ycordview.setText(String.valueOf(event.getY()+v.getTop()));
return true;
}
});
You may consider using GestureDetector to detect swipes, however it isn't really necessary.
karioki 's solution works well. In order to make it work even when we start the move from inside one of the buttons, just add
android:clickable="false"
for every button in xml.