Using Switch Statement to Handle Button Clicks

后端 未结 7 1008
梦毁少年i
梦毁少年i 2020-12-05 03:15

I\'m trying to wrap my head around Views, Listeners etc. I have an Activity with 2 Buttons: buttonplay and buttonstop. My problem is I can\'t wrap my head around the Views

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 03:44

    Just change the class (I suppose it's the main Activity) to implement View.OnClickListener and on the onClick method put the general onClick actions you want to put:

    public class MediaPlayer extends Activity implements OnClickListener {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Button b1 = (Button) findViewById(R.id.buttonplay);       
        b1.setOnClickListener(this);
        //{YOUR APP}
    }
    
    
    @Override
    public void onClick(View v) {
        // Perform action on click
        switch(v.getId()) {
        case R.id.buttonplay:
            //Play voicefile
            MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
            break;
        case R.id.buttonstop:
            //Stop MediaPlayer
            MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
            break;
        }
    
    }}
    

    I took it from this video: http://www.youtube.com/watch?v=rm-hNlTD1H0 . It's good for starters.

提交回复
热议问题