How to create an interface from a class - java

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
}
}

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());

SimpleOnGestureListener not working

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;
}

Having code problems from MainActivity to FragmentActivity

I wrote a simple code in MainActivity with its xml code previously which run successfully. Now, I want to make a fragment and run that MainActivity code in that fragment. I have tried everything, even by combining both codes etc. but all in vain. I'm attaching my MainActivity code below. This is the one I want to use in Fragment. I already know that fragment is like sub-activity of an activity and both have separate xmls too which I also know how to use. Just unable to use my MainActivity code from old app as FragmentActivity in a new app.
1) MainActivity Code which needs to act as a Fragment
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class MainActivity
extends AppCompatActivity
implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private TextView mytext;
private GestureDetector gestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //this is above two lines cox phly content set hoga tbi agy kam hna na
this.gestureDetector = new GestureDetector(this, this);
gestureDetector.setOnDoubleTapListener(this); }
//******************Upon clicking the button*************************
public void changetextshort(View v) {
mytext = (TextView) findViewById(R.id.mytext);
mytext.setText("Surpriseeee"); }
//******************initializing touch event*************************
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);}
//******************Implements Methods from alt+ins(0) for touch properties*************************
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
mytext.setText("I tapped Once");
return false;}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
mytext.setText("I tapped Twice");
return false;}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
mytext.setText("Double Tap Event Occurred");
return false;}
#Override
public boolean onDown(MotionEvent motionEvent) {
mytext.setText("Down goes");
return false;}
#Override
public void onShowPress(MotionEvent motionEvent) {
mytext.setText("I have pressed");}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
mytext.setText("Single Tap Up");
return false;}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I'm Scrolling");
return false;}
#Override
public void onLongPress(MotionEvent motionEvent) {
mytext.setText("I long pressed");}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I FLINNGED");
return false; }
}
2) Fragment Code (MainActivity is not having any code now except the basic code of Mainactivity like class name and OnCreate code - although I have added Mainactivity code in 3rd point too which needs to be actually almost like that when we make fragments in android app)
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TopSectionFragment extends Fragment {
public class Top
extends AppCompatActivity
implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private TextView mytext;
private GestureDetector gestureDetector;
//******************Override method oncreateview for fragment*************************
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment,container, false);
this.gestureDetector = new GestureDetector(this, this);
gestureDetector.setOnDoubleTapListener(this);
return view; //designing of top section fragment completed
}
//******************Upon clicking the button*************************
public void changetextshort(View v) {
mytext = (TextView) findViewById(R.id.mytext);
mytext.setText("Surpriseeee"); }
//******************initializing touch event*************************
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);}
//******************Implements Methods from alt+ins(0) for touch properties*************************
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
mytext.setText("I tapped Once");
return false;}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
mytext.setText("I tapped Twice");
return false;}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
mytext.setText("Double Tap Event Occurred");
return false;}
#Override
public boolean onDown(MotionEvent motionEvent) {
mytext.setText("Down goes");
return false;}
#Override
public void onShowPress(MotionEvent motionEvent) {
mytext.setText("I have pressed");}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
mytext.setText("Single Tap Up");
return false;}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I'm Scrolling");
return false;}
#Override
public void onLongPress(MotionEvent motionEvent) {
mytext.setText("I long pressed");}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I FLINNGED");
return false; }
}
}
3) MainActivity code (which will incorporate Fragment sub-activity)
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity
extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }
}
One of the main things to keep in mind when converting code from activities and fragments is that you may have to switch things that use context in them.
This line: this.gestureDetector = new GestureDetector(this, this); is likely one of the things that is giving you trouble.
This:
GestureDetector(Context context, GestureDetector.OnGestureListener listener)
is probably the constructor you are trying to use.
The parameters that are context, will need to be changed from this in an activity to getContext() (or to something that extends Context) in a fragment.
For creating the fragment in the first place:
https://developer.android.com/guide/components/fragments.html
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
The container mentioned in the code sample is normally something like a FrameLayout.
It is not clear what you mean by "make a fragment and run that MainActivity code in that fragment"...
If you want to start an activity and make it overlay the Fragment you can try the code from MCeley in Start an activity from a fragment
> Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
> startActivity(intent);

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