Question

I'm having a strange issue playing a sound effect when the user touches the screen. I'm really not sure where to go with this. I have a class named sing and a method called sound() that plays the sound effect. In the onCreate() method, the code works fine, but in the onTouch() method, it doesnt. Here is the code I'm using:

TextView textview;
Sing sing;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    textview = new TextView(this);
    textview.setText("Test");
    setContentView(textview);
    sing = new Sing();
    sing.create();
    sing.sound("sound.ogg");//just to test, works fine
}

public boolean onTouch(View v, MotionEvent event){
    if (event.getAction() == MotionEvent.ACTION_UP){
        sing.sound("sound.ogg"); //doesnt work
    } 
    return true;
}

The first call to sing.sound() in onCreate() works fine, but the subsequent call in onTouch() doesn't seem to be doing anything. This test class extends activity and implements onTouch, i've imported onTouch, and beyond that I really dont know what the error could be. I would post the sing class but it's kind of a lot of code. Any help anyone can give would be EXTREMELY appreciated. I've been struggling with this for an embarrassingly long time today, I'm not very good with android yet. Thanks in advance.

--edit Here is the entire activity:

package com.test.ch4;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.view.View;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;

public class SoundPoolTest extends Activity implements OnTouchListener{
TextView textview;
Sing sing;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    textview = new TextView(this);
    textview.setTextSize(40);
    textview.setText("Test");
    setContentView(textview);
}

public boolean onTouch(View v, MotionEvent event){
    if (event.getAction() == MotionEvent.ACTION_UP){
        sing = new Sing();
        sing.create();
        sing.sound("sound.ogg");
    } 
    return true;
    }
}
Was it helpful?

Solution

after

setContentView(textview);

put

textview.setOnTouchListener(this);

then before your onTouch() method put @Override like this

@Override
public boolean onTouch(View v, MotionEvent event){
    if (event.getAction() == MotionEvent.ACTION_UP){
        sing = new Sing();
        sing.create();
        sing.sound("sound.ogg");
    } 
    return true;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top