How do I add a second button android?

前端 未结 2 646
傲寒
傲寒 2021-01-25 05:07

I´ve got a click listener to an email intent in my app, but I want to add a second button to do another thing? Sorry for the dum question, Im a begginer.

For the peoplew

2条回答
  •  我在风中等你
    2021-01-25 05:28

    In the onCreate() you can find your buttons by their id in the your layout XML file, and then add onClickListener to it.

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourLayout); 
    
        button1 = (Button)findViewById(R.id.b1);
        button1.setOnClickListener(this);
    
        button2 = (Button)findViewById(R.id.b2);
        button2.setOnClickListener(this);
    
    
    }
    

    Once you have initialized your buttons you can then use one onClick() method to handle the button clicks, This can be done for many buttons doing different things by using the if statements where arg0 is the name you assigned to the button.

    public void onClick(View arg0) {
    if(arg0 == button1){
        //Do Something
    }
    if(arg0 == button2){
      //Do something
    }
    }
    

提交回复
热议问题