Android touch event

When you build an application in which you want to perform a task when user touch a View, this tip might be useful to you. In this Android tip, I am going to show you how to react to the touch event on a View. For example, when the user touches on a TextView, it is animated. To achieve the goal, you need to call setOnTouchListener() method on the View. The setOnTouchListener() has one argument: an anonymous object that implements the OnTouchListener interface. You need to override the onTouch() method to perform a task when the View is touched. In the example application below, when the user touches the text, the text is animated by changing the Y position of the TextView that displays the text. You can change the Y position of the TextView by calling the translationY() method of the ViewPropertyAnimator object. The ViewPropertyAnimator object is returned by the animate() method of the TextView.
Now to have an example application on reacting to touch event, create a new Android project. Then modify the activity_main.xml file to add one TextView.

<LinearLayout xmlns:android=""

     android:text="Touch me"


In the onCreate() method of the MainActivity class, write code to create a reference to the TextView and call the setOnTouchListener() method as shown below.

package com.example.androidexample;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView myView;
Point size;
protected void onCreate(Bundle savedInstanceState) {
myView = (TextView)findViewById(;
myView.setOnTouchListener(new OnTouchListener() {
   public boolean onTouch(View v, MotionEvent event) {
     //animate the TextView when it is touched
     Display display = getWindowManager().getDefaultDisplay();
      size = new Point();
     myView.animate().translationY(0.0f).withStartAction(new Runnable(){
     public void run(){
     return true;


public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;


Posted by: Dara | post date: 09-20-2014 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.