0
package net.androidbootcamp.guessinggame;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class setting extends Activity {
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);

Button s =(Button) findViewById(R.id.btnons);
s.setOnClickListener(new OnClickListener(){

public void onClick(View v) {


MediaPlayer mp = MediaPlayer.create(setting.this,R.raw.meow);
mp.start();





                }

    });

Button ss =(Button) findViewById(R.id.btnoffs);
ss.setOnClickListener(new OnClickListener(){

如何对关闭按钮进行编码。这是我的打开按钮代码。我不知道如何在单击另一个按钮(关闭)时停止声音。

 I have two buttons, the ON and OFF button,a normal game settings of sound.

我不知道接下来会发生什么。每次单击OFF按钮时,我都想停止停止。

4

1 回答 1

0

这可能足以处理MediaPlayer代码中的存在:

package net.androidbootcamp.guessinggame;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class setting extends Activity {
    private MediaPlayer mediaPlayer;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        Button s =(Button) findViewById(R.id.btnons);
        s.setOnClickListener(
            new OnClickListener(){
                @Override
                public void onClick(View v) {
                    startMediaPlayer();
                }
            }
        );

        Button ss =(Button) findViewById(R.id.btnoffs);
        ss.setOnClickListener(
            new OnClickListener(){ 
                @Override
                public void onClick(View v) {
                    stopMediaPlayer();
                }
            }
        );
    }

     private void startMediaPlayer() {
        mediaPlayer = MediaPlayer.create(setting.this,R.raw.meow);
        mediaPlayer.start();
    }

    private void stopMediaPlayer() {
        if( mediaPlayer != null ) {
            mp.stop();
            mp.release();
        }
    }
}

对您的代码的更改: mp现在是该类的成员setting,称为mediaPlayer. 以前,您很难尝试mp在“关闭按钮”的范围内工作OnClickListener,但现在已经解决了。还使用空检查将代码包装起来stopMediaPlayer()以避免NullPointerException.

于 2013-01-12T13:05:01.220 回答