Using Switch Statement to Handle Button Clicks

后端 未结 7 850
梦毁少年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 04:08

    Hi its quite simple to make switch between buttons using switch case:-

     package com.example.browsebutton;
    
    
        import android.app.Activity;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.Toast;
    
            public class MainActivity extends Activity implements OnClickListener {
            Button b1,b2;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    b1=(Button)findViewById(R.id.button1);
    
                    b2=(Button)findViewById(R.id.button2);
                    b1.setOnClickListener(this);
                    b2.setOnClickListener(this);
                }
    
    
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
    
                     int id=v.getId();
                     switch(id) {
                        case R.id.button1:
                      Toast.makeText(getBaseContext(), "btn1", Toast.LENGTH_LONG).show();
                    //Your Operation
    
                      break;
    
                        case R.id.button2:
                              Toast.makeText(getBaseContext(), "btn2", Toast.LENGTH_LONG).show();
    
    
                              //Your Operation
                              break;
                }
    
            }}
    
    0 讨论(0)
提交回复
热议问题