简体   繁体   English

如何在触摸按钮时启用声音效果?

[英]How to enable the sound effect on touching a button?

If I implement the OnClickListener , the sound effect will work on clicking the button. 如果我实现OnClickListener ,则在单击该按钮时会产生声音效果。 While on implementing the OnTouchListener the sound effect doesn't work on touching it. 在实现OnTouchListener ,触摸声音效果不起作用。 So how to enable the sound effect on implementing the OnTouchListener ? 那么如何在实现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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM