The setOnTouchListener method is used in the Android.widget.TextView class in the Android SDK library. This method sets a touch listener for the given TextView object, allowing you to respond to various touch events within the TextView.
Example 1: Using setOnTouchListener to change the background color of a TextView when it is pressed:
TextView text = findViewById(R.id.textView); text.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: v.setBackgroundColor(Color.BLUE); break; case MotionEvent.ACTION_UP: v.setBackgroundColor(Color.TRANSPARENT); break; } return true; } });
This code creates a TextView object and sets an onTouchListener for it. When the TextView is touched (ACTION_DOWN), the background color is changed to blue. When the touch is released (ACTION_UP), the background color is set back to transparent.
Example 2: Using setOnTouchListener to detect a swipe gesture on a TextView:
TextView text = findViewById(R.id.textView); text.setOnTouchListener(new View.OnTouchListener() { private GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1.getX() < e2.getX()) { //swipe right return true; } else { //swipe left return true; } } });
This code creates a GestureDetector object to detect swipe gestures on the TextView. When a swipe is detected (onFling), the direction of the swipe is determined and appropriate action is taken.
Package: android.widget
Java TextView.setOnTouchListener - 30 examples found. These are the top rated real world Java examples of android.widget.TextView.setOnTouchListener extracted from open source projects. You can rate examples to help us improve the quality of examples.