If I implement the OnClickListener, the sound effect will work on clicking the button. While on implementing the OnTouchListener the sound effect doesn't work on touching it. So how to enable the sound effect on implementing the OnTouchListener?

EDIT:

Here is the code if I use clicking approach:

public class CalculatorActivity extends Activity implements OnClickListener
{
    //...
    private Button btn1;
    private EditText edLCD;
    //...

    public void onCreate(Bundle savedInstanceState)
    {
        //...
        btn1 = (Button) findViewById(R.id.d1);
        btn1.setOnClickListener(this);

        edLCD = (EditText) findViewById(R.id.edLCD);
    }

    //...

    public void onClick(View v)
    {
        edLCD.setText(edLCD.getText().toString() + "1");
    }
}

And here is the code if I use touching approach:

public class CalculatorActivity extends Activity implements OnTouchListener
{
    //...
    private Button btn1;
    private EditText edLCD;
    //...

    public void onCreate(Bundle savedInstanceState)
    {
        //...
        btn1 = (Button) findViewById(R.id.d1);
        btn1.setOnTouchListener(this);

        edLCD = (EditText) findViewById(R.id.edLCD);
    }

    //...

    public boolean onTouch(View v, MotionEvent event)
    {
        if(event.getAction() == MotionEvent.ACTION_DOWN)
        {
            edLCD.setText(edLCD.getText().toString() + "1");
        }
        return true;
    }
}
有帮助吗?

解决方案

Try...

public boolean onTouch(View v, MotionEvent event)
{
    if(event.getAction() == MotionEvent.ACTION_DOWN)
    {
        v.playSoundEffect(SoundEffectConstants.CLICK);
        edLCD.setText(edLCD.getText().toString() + "1");
    }
    return true;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top