How To Make An Android App To Count The Number Of Touch Events
In this post we will make an app which will count the number of time you touch the screen in android studio .It is quite easy to do this in a very few steps so now lets get started.
1 Design
In this phase we will only add text view in out XML and here is the code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activity_main"
tools:context="com.example.surhan.touchapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/counter"
android:textSize="50dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
2 Java Code
Now we will use java to write the code for the touch app.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RelativeLayout myLayout = null;
private int count=0;
private String Count;
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLayout = (RelativeLayout) findViewById(R.id.activity_main);
textview = (TextView) findViewById(R.id.counter);
myLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN)
{
count++;
Count=Integer.toString(count);
textview.setText(Count);
}
return true;
}
});
}
}
Now let Discuss this we are using the MotionEvent to call a specific function call ACTION_DOWN which means when the screen is pressed when the screen is pressed it call that event and then adding it to out Integer count , saving the amount of times when you press the screen and then passing the count value to textview. Now why did i used the IF statement is that if a only use motioneven then when you touch the screen it will count it as 2 times because there two events being called one is ACTION_DOWN and ACTION_UP .Down means when the screen is pressed and Up means when you release you finger from the screen.
3 Conclusion
So what we learn today was that is we build an app that counts the number of times we touch the screen.So if you have any problems please let us know.
Comments
Post a Comment