Using Switch Statement to Handle Button Clicks

后端 未结 7 1014
梦毁少年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:02

    One mistake what i did was not including "implements OnClickListener" in the main class declaration. This is a sample code to clearly illustrate the use of switch case during on click. The code changes background colour as per the button pressed. Hope this helps.

    public class MainActivity extends Activity  implements OnClickListener{
    
    
    TextView displayText;
    Button cred, cblack, cgreen, cyellow, cwhite;
    LinearLayout buttonLayout;
    
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        cred = (Button) findViewById(R.id.bred);
        cblack = (Button) findViewById(R.id.bblack);
        cgreen = (Button) findViewById(R.id.bgreen);
        cyellow = (Button) findViewById(R.id.byellow);
        cwhite = (Button) findViewById(R.id.bwhite);
        displayText = (TextView) findViewById(R.id.tvdisplay);
        buttonLayout = (LinearLayout) findViewById(R.id.llbuttons);
    
        cred.setOnClickListener(this);
        cblack.setOnClickListener(this);
        cgreen.setOnClickListener(this);
        cyellow.setOnClickListener(this);
        cwhite.setOnClickListener(this);
    }
    
    @Override
    protected void onClick(View V){
        int id=V.getId();
        switch(id){
        case R.id.bred:
            displayText.setBackgroundColor(Color.rgb(255, 0, 0));
            vanishLayout();
            break;
        case R.id.bblack:
            displayText.setBackgroundColor(Color.rgb(0, 0, 0));
            vanishLayout();
            break;
        case R.id.byellow:
            displayText.setBackgroundColor(Color.rgb(255, 255, 0));
            vanishLayout();
            break;
        case R.id.bgreen:
            displayText.setBackgroundColor(Color.rgb(0, 255, 0));
            vanishLayout();
            break;
        case R.id.bwhite:
            displayText.setBackgroundColor(Color.rgb(255, 255, 255));
            vanishLayout();
            break;
        }
    }
    

提交回复
热议问题