recently one of my reader sunilkumar tk wanted to share sample code to get the touch co-ordinates in android using java programming what does this code do? it simply grabs and returns the co-ordinates or location of the screen where the user has touched below is the sample code for the same.
package com.TouchScreen;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class TouchScreen extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView)findViewById(R.id.textView);
// this is the view on which you will listen for touch events
final View touchView = findViewById(R.id.touchView);
touchView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
return true;
}
});
}
}
if you want the complete working code you can download it from Here , btw please penn in your suggestion and improvements about the program in comment section hope sunil will be a regular contributor for android programming sample snippets here and share his idea with rest of the world.
2 comments:
Hi I am new to Android programming and this is a great help but I am unable to get the working code... the link doesn't seem to work.. Any other way I could get it?
Nirali, try those two things:
1) Make sure your package name agrees with yours.
2) Make sure you have a file main.xml inside res/layout which has a TextView called "textView" and a View called "touchView".
Post a Comment