SimpleOnGestureListener not working - java

I want to change between activities by swiping in my MainActivity. I declared an object from GestureDetectorCompat and initialized it in method onCreate like that:
gestureObject = new GestureDetectorCompat(MainActivity.this, new GestureListener());
Also, I override onTouchEvent like that:
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureObject.onTouchEvent(event);
return super.onTouchEvent(event);
}
and my MainActivity extends from AppCompatActivity and implements NavigationView.OnNavigationItemSelectedListener, OnMenuItemClickListener.
GestureListener code is:
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public void onLongPress(MotionEvent e) {
Log.e(TAG, "long pressed");
super.onLongPress(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e(TAG, "on Flig");
if (e2.getX() > e1.getX()) {
Log.e(TAG, "left to right");
}
return true;
}
}
but it does not work.
Is it related to navigationView?
What can I do?

Try this code..
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
public class MainActivity extends AppCompatActivity {
private GestureDetectorCompat mDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDetector = new GestureDetectorCompat(MainActivity.this, new SwipeGestureDetector());
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
this.mDetector.onTouchEvent(motionEvent);
return super.onTouchEvent(motionEvent);
}
#Override
public boolean dispatchTouchEvent(#NonNull MotionEvent ev) {
super.dispatchTouchEvent(ev);
return mDetector.onTouchEvent(ev);
}
/**
* Swipe Gesture Detector Class for swipe detector.
*/
public class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if(e1 == null || e2 == null)
return false;
if(e1.getPointerCount() > 1 || e2.getPointerCount() > 1)
return false;
else {
try {
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
if(Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > 100 && Math.abs(velocityX) > 1000) {
if ((diffX > 0) || (diffX < 0)) {
// nextActivity();
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
}
}

Try this,
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureObject.onTouchEvent(event);
return true;
}

Related

Cleaning up a one file project

So I'm working on a project and am using a lot of code or atleast a decent amount all in one file and am wondering if there is a way to clean it up into multiple files. I've only every worked with single file. So when It come to adding more files I'm not really sure how to go about this so I'm gonna ask for help on cleaning up the project. the ideal outcome is to have it more understandable via small chunks in other files to clean up the CoreActivity. or if you see a way to clean up some code into a easier and less exhaustive way of writing it then do fix
CoreActivity.java
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import com.github.pwittchen.gesture.library.Gesture;
import com.github.pwittchen.gesture.library.GestureListener;
import com.github.pwittchen.swipe.library.rx2.Swipe;
import com.github.pwittchen.swipe.library.rx2.SwipeListener;
public class CoreActivity extends AppCompatActivity {
//Widgets
ConstraintLayout m_Preference_Toolbar;
ConstraintLayout m_Toolbar;
ConstraintLayout m_Preferences;
EditText m_WebView_Search;
WebView m_WebView;
private Swipe WebSwipe;
private Gesture WebGesture;
//Variables
String Url = "https://www.Google.ca";
int WebS =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_core);
//Find Views
m_Toolbar = findViewById(R.id.m_Toolbar);
m_Preferences = findViewById(R.id.m_Preferences);
m_WebView_Search = findViewById(R.id.m_WebView_Search);
m_WebView = findViewById(R.id.m_WebView);
m_Preference_Toolbar = findViewById(R.id.m_Preferences_Toolbar);
m_Preference_Toolbar.setVisibility(View.GONE);
m_Preferences.setOnTouchListener(new View.OnTouchListener() {
Animation ToolbarGone,ToolbarPrefVisible;
int x = 0;
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
m_Preferences.setVisibility(View.GONE);
x =1;
ToolbarGone = AnimationUtils.loadAnimation(CoreActivity.this, R.anim.m_toolbar_gone);
m_Toolbar.startAnimation(ToolbarGone);
if(m_Preferences.getVisibility() == View.GONE || x == 1) {
ToolbarPrefVisible = AnimationUtils.loadAnimation(CoreActivity.this, R.anim.m_preference_toolbar_appear);
m_Preference_Toolbar.startAnimation(ToolbarPrefVisible);
}
return false;
}
});
//m_WebView
final WebSettings m_WebViewSetting = m_WebView.getSettings();
m_WebView.setWebViewClient(new WebViewClient());
m_WebViewSetting.setJavaScriptEnabled(true);
m_WebViewSetting.setSupportZoom(true);
m_WebViewSetting.setLoadWithOverviewMode(true);
m_WebViewSetting.setUseWideViewPort(true);
m_WebView.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
m_WebView.loadUrl(Url); //Default HomePage
//m_WebView_Search TextView and Keyboard
m_WebView_Search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
if (m_WebView_Search.getText().toString().contains(".com")
|| m_WebView_Search.getText().toString().contains(".ca")
|| m_WebView_Search.getText().toString().contains(".net")
|| m_WebView_Search.getText().toString().contains(".org")) {
Url = m_WebView_Search.getText().toString();
m_WebView.loadUrl("https://www." + Url);
m_WebView_Search.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(m_WebView_Search.getWindowToken(), 0);
} else {
if (m_WebView_Search.getText().toString().contains("")) {
Url = m_WebView_Search.getText().toString();
m_WebView.loadUrl("https://www.google.ca/search?q=" + Url);
m_WebView_Search.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(m_WebView_Search.getWindowToken(), 0);
}
}
}
return false;
}
});
//Swipe Events WebSwipe
WebSwipe = new Swipe(350, 700);
WebSwipe.setListener(new SwipeListener() {
int Web = 0;
Animation WebShrink, WebEnlarge;
#Override
public void onSwipingLeft(final MotionEvent event) {
if(m_WebView.canGoForward()){
m_WebView.goForward();
}
else{
m_WebView.reload();
}
}
#Override
public void onSwipedLeft(final MotionEvent event) {
}
#Override
public void onSwipingRight(final MotionEvent event) {
if(m_WebView.canGoBack()){
m_WebView.goBack();
}
else{
m_WebView.reload();
}
}
#Override
public void onSwipedRight(final MotionEvent event) {
}
#Override
public void onSwipingUp(final MotionEvent event) {
}
#Override
public void onSwipedUp(final MotionEvent event) {
//WebView Animation (Enlarge)
if(Web == 0){
WebEnlarge = AnimationUtils.loadAnimation(CoreActivity.this, R.anim.m_webview_enlarge);
m_WebView.startAnimation(WebEnlarge);
Web = 1;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
m_Toolbar.setVisibility(View.GONE);
}
}, 350);
}
}
#Override
public void onSwipingDown(final MotionEvent event) {
}
#Override
public void onSwipedDown(final MotionEvent event) {
//WebView Animation (Shrink)
if(Web == 1){
WebShrink = AnimationUtils.loadAnimation(CoreActivity.this,R.anim.m_webview_shrink);
m_WebView.startAnimation(WebShrink);
m_Preference_Toolbar.setVisibility(View.GONE);
Web = 0;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
m_Toolbar.setVisibility(View.VISIBLE);
}
}, 350);
}
}
});
WebGesture = new Gesture();
WebGesture.addListener(new GestureListener() {
#Override public void onPress(MotionEvent motionEvent) {
}
#Override public void onTap(MotionEvent motionEvent) {
}
#Override public void onDrag(MotionEvent motionEvent) {
}
#Override public void onMove(MotionEvent motionEvent) {
}
#Override public void onRelease(MotionEvent motionEvent) {
}
#Override public void onLongPress(MotionEvent motionEvent) {
}
#Override public void onMultiTap(MotionEvent motionEvent, int clicks) {
}
});
}
#Override
public boolean dispatchTouchEvent (MotionEvent event){
WebSwipe.dispatchTouchEvent(event);
WebGesture.dispatchTouchEvent(event);
return super.dispatchTouchEvent(event);
}
}
The simplest way to split code is to think about Single Responsibility (as per the SOLID principles).
As an example in your code, your touch listener can be separated. This would entail making a class that extended the touch listener's class (View.OnTouchListener) instead of extending an activity.
This block in your code:
m_Preferences.setOnTouchListener(new View.OnTouchListener() {
...
});
Would become MyTouchListener.java:
public class MyTouchListener implements View.OnTouchListener {
Animation ToolbarGone,ToolbarPrefVisible;
int x = 0;
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
... // keep exactly your same code here
}
}
And then your activity gets changed to:
m_Preferences.setOnTouchListener(new MyTouchListener());

How to create an interface from a class

I am new to Android Programming/ Java I wanted to know how I should add gesture Directions when I already have a class extended to MainActvity?
package #####app.myapplication;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener{
private GestureDetectorCompat mygesture;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
#Override
public void onShowPress(MotionEvent motionEvent) {
}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
#Override
public void onLongPress(MotionEvent motionEvent) {
}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mygesture.onTouchEvent(event);
return super.onTouchEvent(event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
CharSequence text = "Welcome to ####";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
WebView vedant = (WebView) findViewById(R.id.vedant);
vedant.loadUrl("http://##.ml");
WebSettings webSettings = vedant.getSettings();
webSettings.setJavaScriptEnabled(true);
vedant.setWebViewClient(new WebViewClient());
this.mygesture = new GestureDetectorCompat(this,this);
mygesture.setOnDoubleTapListener(this);
}
}
I know that to use Gesture Direction I need to :
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH){
return false;
}
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
onLeftSwipe();
}
// left to right swipe
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
onRightSwipe();
}
} catch (Exception e) {
}
return false;
}
return false;
}
But for which I need to extend another class SimpleOnGestureListener.
As i could not extend to the SimpleOnGestureListener class I thought i could create a interface and then implement it. Is that possible. If so how?
If I understand correctly, you have a GestureDetectorCompat with 2 parameters:
The Context
a listener (GestureDetector.OnGestureListener)
At the moment you do mygesture = new GestureDetectorCompat(this,this); where this is your Activity. But why do you want your Activity to be the listener? You can create a listener in a separated class.
So you can do:
MainActivity
this.mygesture = new GestureDetectorCompat(this, new MyGestureListener());
MyGestureListener
public class MyGestureListener extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
// ...
// Your code
}
}

How to use if statements with gestures sequentially in Android Studio?

I'm trying to setup a way to only accept one gesture at a time then after that gesture is done do the next in line. So for example I want to start with a single tap then after you input the tap it would move on to the next one being a double tap. Here's the code I'm using:
import android.content.DialogInterface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
public class secondscreen extends ActionBarActivity implements GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener{
private TextView mainMessage; //variable refers to strings.xml// private TextView InText;
private TextView startButton;
private GestureDetectorCompat gestureDetector; // Secondary Variable used for gestures
private DialogInterface.OnClickListener OnClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondscreen2);
mainMessage = (TextView) findViewById(R.id.mainMessage);
this.gestureDetector = new GestureDetectorCompat(this, this);
gestureDetector.setOnDoubleTapListener(this);
}
///////// GESTURE METHODS //////////
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
mainMessage.setText("single tap");
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
mainMessage.setText("double tap");
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
mainMessage.setText("double tapping event");
return false;
}
#Override
public boolean onDown(MotionEvent e) {
mainMessage.setText("down");
return false;
}
#Override
public void onShowPress(MotionEvent e) {
mainMessage.setText("showing the press");
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
mainMessage.setText("tap up");
return false;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
mainMessage.setText("scrolling is fun");
return false;
}
#Override
public void onLongPress(MotionEvent e) {
mainMessage.setText("very long presses");
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mainMessage.setText("flinging");
return false;
}
///////// GESTURE METHODS //////////
//this next block is needed to run gestures//
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_secondscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I specifically want the gestures to not happen at the same time as it is set up now, the app will run the gestures and display a text but it does it all at the same time displaying the last one pressed - I want to know how to set it up on one screen so that it asks for a gesture and moves on to the next gesture after that one is pressed preferably waiting a second so it doesn't happen instantly. I'm pretty sure it has something to do with an if else statement but I have no idea how to word it.
One simple way I can think of is to just use an enum combined with if statements
enum ex.
private enum EVENT{
SINGLE_TAP,DOUBLE_TAP,EVENT_3,EVENT_4 ...;
}
private EVENT currentEvent=EVENT.SINGLE_TAP;
Event Handler
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (currentEvent==Event.SINGLE_TAP){
mainMessage.setText("single tap");
currentEvent=Event.DOUBLE_TAP;//set to next desired event
return true;
}
return false;
}
Do something similar in your other event handlers, on the last event i would make it loop back to the first
If you desire a delay between the events implement a stopwatch and check if your desired time has passed between events. Something like so.
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if(stopWatch.getTime > lastEventTime+delay){//pseudo code
if (currentEvent==Event.SINGLE_TAP){
mainMessage.setText("single tap");
currentEvent=Event.DOUBLE_TAP;//set to next desired event
return true;
}
}
return false;
}

Android game loop thread crash

I am very new to programming and I have a problem with a game which I am trying to make.
Almost every time when I exit the game it was crashing.
After adding: if (canvas != null) beforew canvas.drawColor(Color.CYAN); it does not crash on exit anymore but when I return to the game.
Here is the code: (its not my actual game... there is nothing in OnDraw exept canvas.drawColor(Color.CYAN); that keeps it simple)
GameView.java:
package com.example.test.threadtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread theGameLoopThread;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onDraw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(Color.CYAN);
}
}
GameLoopThread.java:
package com.example.test.threadtest;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView theView;
private boolean isRunning = false;
public GameLoopThread(GameView theView) {
this.theView = theView;
}
public void setRunning(boolean run) {
isRunning = run;
}
#SuppressLint("WrongCall") #Override
public void run() {
long TPS = 1000 / FPS;
long startTime, sleepTime;
while (isRunning) {
Canvas theCanvas = null;
startTime = System.currentTimeMillis();
try {
theCanvas = theView.getHolder().lockCanvas();
synchronized (theView.getHolder()) {
theView.onDraw(theCanvas);
}
} finally {
if (theCanvas != null) {
theView.getHolder().unlockCanvasAndPost(theCanvas);
}
}
sleepTime = TPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
}
MainAcitvity.java:
package com.example.test.threadtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

play sound while button is pressed -android

i have this code
package com.tct.soundTouch;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
public class main extends Activity implements OnTouchListener {
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button zero = (Button) this.findViewById(R.id.button);
zero.setOnTouchListener(this);
mp = MediaPlayer.create(this, R.raw.sound);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mp.setLooping(true);
mp.start();
case MotionEvent.ACTION_UP:
mp.pause();
}
return true;
}
}
and it works but not as i expected. The sound plays but only for each time that i press the button. My idea is. While i press the button the sound plays, when i stop the action (finger out of the button) music pause.
Any idea please?
thanks
This should work (there was something wrong with your switch-cases I think):
#Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
break;
case MotionEvent.ACTION_UP:
{
mediaPlayer.pause();
}
break;
}
return true;
}
public class MainActivity extends AppCompatActivity {
Button button;
MediaPlayer player;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
button = findViewById( R.id.Click );
button.setOnTouchListener( new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()== MotionEvent.ACTION_DOWN) {
player= MediaPlayer.create( MainActivity.this,R.raw.horn );
player.start();
}
else if(event.getAction()==MotionEvent.ACTION_UP){
player.stop();
player.release();
}
return true;
}
} );
}
}

Categories