How to play audio only while button is held down? - java

I am trying to make a simple app: there is one button in the middle which a child would press. As long as that button is held down it would play a certain MP3.
At the moment, I tried with onClick, but, that plays only when the button is released.

Instead of using an onClickListener which exposes nothing more then an interface for press and release, you would need to use an onTouchListener - which exposes all touch events of a view.
myButton.setOnTouchListener( new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch ( event.getAction() ) {
MotionEvent.ACTION_DOWN:
// start playing
return true;
MotionEvent.ACTION_UP:
// stop playing
return true;
}
return false;
}
});

Try something like this. Using the boolean "playing" you can create a thread/loop elsewhere to check if still playing and keep audio going.
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction()==MotionEvent.ACTION_DOWN) {
playing = true;
} else {
playing = false;
}
return true;
}
});

Try the OnFocusChangeListener
Button.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when Button loses focus, i.e. stop music
}
}
});

Since a button is a view component you can use View.OnTouchListener event listener with ACTION_BUTTON_PRESS & ACTION_BUTTON_RELEASE MotionEvent.
Here is an example:
yourButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_BUTTON_PRESS){
// Start Video
return true;
} else if (event.getAction() == MotionEvent.ACTION_BUTTON_RELEASE) {
// End Video
return true;
}
return false;
}
});

This is my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start_recording(View view){
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.test1);
mediaPlayer.start();
}
}

Related

Android: EditText onclick content

My Question is lightweight. I wish to know how do I set a click event inside an EditText also determining which drawable or word is pressed. Basically I have an EditText that can contain word-wrapped drawables or static text.
So I'm expecting something like this:
editText.setOnCustomPressListener(new OnCustomPressListener(){
void onWordTapped(String text){
}
void onAttachmentTapped(CharSequence ch){
}
})
Please help, I've been looking for weeks.
Are you looking for this?
mEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
It would be good to see more code (your xml)
This is not ideal but this is working anyway.
editText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
int startSelection = editor.getSelectionStart();
int endSelection = editor.getSelectionEnd();
String selectedText = editor.getText().toString().substring(startSelection, endSelection);
AppConfig.quicktoast(selectedText);
}
return false;
}
});

Neither onKeyListener nor TextWatcher able to receive soft keyboard inputs

I have looked at many posts and similiar questions have been asked. But none of the solution is working. First of all I've tried using onKeyListener, but in many posts, it is stated that it does not work for soft keyboard. So I tried to use TextWatcher instead, but it still does not printout anything.
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback{
private MainThread thread;
private EditText editText;
private Bitmap textBitmap;
public GamePanel(Context context){
super(context);
//Add callback to the surfaceview to intercept events
getHolder().addCallback(this);
//Make GamePanel focusable so it can handle events
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,int width, int height){}
#Override
public void surfaceDestroyed(SurfaceHolder holder){}
#Override
public void surfaceCreated(SurfaceHolder holder){
editText = new EditText(getContext());
editText.setSingleLine(true);
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
editText.setDrawingCacheEnabled(true);
editText.layout(0, 0, WIDTH - 200, 100);
editText.buildDrawingCache();
textBitmap = Bitmap.createBitmap(editText.getDrawingCache());
thread = new MainThread(getHolder(), this);
//Start the game loop
thread.setRunning(true);
thread.start();
/*editText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
Toast.makeText(getContext(), "ABCD", Toast.LENGTH_SHORT).show();
System.out.println("KEY PRESSED");
}
return true;
}
});*/
/*editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
System.out.println("KEY PRESSED");
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("KEY PRESSED");
}
});*/
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
System.out.println("ABC");
return true;
}
return false;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_DOWN ){
editText.setFocusableInTouchMode(true);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
//imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
return true;
}
return super.onTouchEvent(event);
}
#Override
public void draw(Canvas canvas){
if (canvas != null) {
canvas.drawBitmap(textBitmap,50,50,null);
canvas.restoreToCount(savedState);
}
}
Does drawing EditText with canvas.drawBitmap have anything to do with those solutions not working? Or is there any mistakes on implementing them?
Any solutions are welcomed, need explanations if possible. Thanks!
EDIT : tried to use onEditorActionListener
First of all check
Did you include this line in your xml inside the EditText
android:singleLine="true"
if not, please add it first.
Next for e.g i wanna use Done button inside my soft keyboard, than here is what you can do.
<EditText
android:id="edName"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:singleLine="true" //this line to take input in single line (if you don't include this line, Done button will not take any actions)
android:imeOptions="actionDone"/> //this line to provide done button
Now to take the input from keyboard for done button, add this code after findViewById in your onCreate
//TODO softKey "Done" listener for keyboard
edName.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//Do what you want here
return true;
}
return false;
}
});

Android do not execute setOnTouchListener if setOnLongClickListener has been executed

I have an app where you can press on a screen and a method gets executed, and where you can long press and another method gets executed. The problem is, when I long press on the screen the normal onClickListener also gets executed, which I don't want.
They both are simple onClickListeners, the normal one is using the MotionEvent ACTION_UP. Is there any way to prevent that from happening?
So I don't want to execute the ACTION_UP in the normal onTouchListener when the onLongClickListener executed.
Code:
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return false;
}
});
layout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
If you still want to onTouch
int flag=0
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if(flag==0){
//do something
}else{
flag=0;
}
}
return false;
}
});
layout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
flag=1
return true;
}
});
LongClick and Click are in the same level, while Touch isn't (actually LongClick an Click are dispatched from onTouchEvent).
In your code, you always return false in onTouch method, so you don't comsume the event and it will be passed to the next level (LongClick, Click...), this is why when you long press the screen you have the both method called.
Suggestion1:
Use ClickListener instead of TouchListener.
Suggestion2:
Use GestureDetector to handle all events (touch, longclick...). This is an example
Suggestion3:
Use a flag to perform the desired event.
private boolean longClick = false;
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (longClick) {
longClick = false;
}
return false;
}
});
layout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
longClick = true;
return false;
}
});
Suggestion4:
Use a handler with runnable. Example1 and Example2
If onclick does the same as you intended use onclick listner instead of ontouch that way you wont trigger onclick when you longclick.

Losing Activity focus after Contextual Voice Commands

I am trying to implement contextual voice commands in my Glass application described in the documentation.
I have a FrameLayout inside my layout, and in my activity I'm implementing OnKeyDown in order to recognize taps. However, when the user says "Ok glass" and then selects one of the available commands, the same activity is returned, but unresponsive (I can't even close the app by sliding down).
I tried to use requestFocus() on the FrameLayout in a couple of different ways, but it did not have any effects. How could I have the focus back without having to restart the activity?
Essentially, this is the code I have so far for the main activity:
public class MainActivity extends Activity {
public static String TAG = "DummyProject::MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(WindowUtils.FEATURE_VOICE_COMMANDS);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == WindowUtils.FEATURE_VOICE_COMMANDS) {
getMenuInflater().inflate(R.layout.main, menu);
return true;
}
return super.onCreatePanelMenu(featureId, menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == WindowUtils.FEATURE_VOICE_COMMANDS) {
switch (item.getItemId()) {
case R.id.awesome:
Log.i(TAG, "Selected!");
break;
default:
return true;
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public boolean onKeyDown(int keycode, KeyEvent event) {
if(keycode == KeyEvent.KEYCODE_DPAD_CENTER) {
Log.i(TAG, "tap!");
return true;
}
return super.onKeyDown(keycode, event);
}
}
For this example, onKeyDown does not get called after I select any of the "ok glass" menu options.
Thank you in advance.
prefer GestureDetector for catching touch pad events...
...
private GestureDetector mGestureDetector;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mGestureDetector = createGestureDetector(this);
...
}
...
private GestureDetector createGestureDetector(Context context) {
GestureDetector gestureDetector = new GestureDetector(context);
// Create a base listener for generic gestures
gestureDetector.setBaseListener(new GestureDetector.BaseListener() {
#Override
public boolean onGesture(Gesture gesture) {
if (gesture == Gesture.TAP) {
Log.d(TAG, "TAP!!!");
return true;
}
return false; }
});
gestureDetector.setFingerListener(new GestureDetector.FingerListener() {
#Override
public void onFingerCountChanged(int previousCount, int currentCount) {
// do something on finger count changes
}
});
gestureDetector.setScrollListener(new GestureDetector.ScrollListener() {
#Override
public boolean onScroll(float displacement, float delta, float velocity) {
// do something on scrolling
return true;
}
});
return gestureDetector;
}
/*
* Send generic motion events to the gesture detector
*/
#Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onMotionEvent(event);
}
return false;
}
It turns out that the problem was with the Manifest file. I was setting a theme to the application, ie.
<application android:theme="#android:style/Theme.NoTitleBar"> ...
Once I removed the theme, everything worked perfectly. The GDK demo sample by Google was helpful when I was trying to find this odd error.

How to use touch and double click on the image..?

I have one imageview, if i touch the imageview it to do some action else if i double click that imageview need to do some action.
How it is possible.?
First create a GestureDetector and a listener. Then bind it to your class that extends GestureDetector.SimpleOnGestureListener.
private GestureDetector detector;
private ImageView mImageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
detector = new GestureDetector(this, new MyGesturesListener());
// TODO find your image view
mImageView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
detector.onTouchEvent(event);
return true;
}
});
}
Then you can implement the methods of different gestures:
class MyGesturesListener extends GestureDetector.SimpleOnGestureListener{
#Override
public boolean onSingleTapUp(MotionEvent ev) {
// TODO handle single tap
return true;
}
#Override
public boolean onDoubleTap(MotionEvent ev) {
// TODO handle double tap
return true;
}
}

Categories