按钮onClickListener无法在Android中播放声音

时间:2018-05-04 22:23:36

标签: java android button listener onclicklistener

我试图设置我的按钮在点击时播放一首歌,但没有任何反应,没有错误,没有强制退出。当我单击渲染中的按钮时,它只是按下。

public class Shows extends AppCompatActivity {
    RadioButton radRent1, radRent2, radWicked, radHamilton, radPhantom;
    Button btnRent, btnWicked, btnHamilton, btnPhantom;
    MediaPlayer mpRent1,mpRent2, mpWicked, mpHamilton, mpPhantom;
    int playing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shows);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(Shows.this, ItemListActivity.class));
            }
        });
        playing = 0;
        mpRent1 = new MediaPlayer();
        mpRent1 = MediaPlayer.create(this, R.raw.seasons_of_love);
        mpRent2 = new MediaPlayer();
        mpRent2 = MediaPlayer.create(this, R.raw.seasons_of_love);
        btnRent = (Button)findViewById(R.id.btnRent);
        btnRent.setOnClickListener(bRent);
    }
    Button.OnClickListener bRent = new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch(playing){
                case 0:
                    mpRent1.start();
                    playing = 1;
                    btnRent.setText("Pause Selected Song");
                    break;
                case 1:
                    mpRent1.pause();
                    playing = 0;
                    btnRent.setText("Play Selected Song");
                    break;
            }
        }
    };

}

任何人都可以看到错误的位置吗?

2 个答案:

答案 0 :(得分:0)

您需要启用查看ID

或 在bRent上使用set onClickListener

`

 bRent.setOnClickListener(new View.OnClickListener() {                                                                
 @Override
 public void onClick(View view){                                              
 //put your logic here                                                       
 }`

答案 1 :(得分:0)

以这种方式设置动作

 playbutton.setOnClickListener(this);
 pausebutton.setOnClickListener(this);

然后实施

  implements View.OnClickListener

比覆盖

  @Override
public void onClick(View view) {
    switch(view.getId()) {
        case R.id.play:
            //Play voicefile

            break;
        case R.id.pause:
            //Stop MediaPlayer

            break;
    }
}