How do I add a second button android?

前端 未结 2 618
傲寒
傲寒 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:23

    First define your button variables in your activity/fragment

    Button button1;
    Button button2;
    

    In the onCreate (activity) or onCreateView (fragment) method, link the button objects to the buttons in your layout, and set their onClickListeners:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        button1= (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                //do something
            }
        });
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                //do something else
            }
        });
    }
    

    Your layout file should then have something like this:

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button1" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button2" />    
    
    0 讨论(0)
  • 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
    }
    }
    
    0 讨论(0)
提交回复
热议问题