Buttons

Creating a Button object:
(Creating Views as Java Objects)

public class MainActivity extends AppCompatActivity {

    Button clickMe;
    TextView hello;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hello = findViewById(R.id.helloLabel);
        clickMe = findViewById(R.id.b1);

    }

}

The code above creates a TextView and a Button. The ID values of those objects must match the ID of views in your layout file.

Define a Method

When the button is clicked, I want to call this method:

    public void clicked(View v){
        hello.setText("Button was clicked.");
    }

This method changes the text of the hello TextView. It won’t work if you don’t include “View v” in the method parameters like it shows above.

Where to put the method:

The method has to go inside the class but not inside another method.

Pay close attention to the curly braces to get it in the right part of your code. The method goes after the closing curly brace for the onCreate() method in the example above.

Set the Button’s onClick Attribute:

So far we’ve defined a method and created a Button, but the method isn’t connected to the Button. We need to set the onClick attribute to fix that.

Using Layout Designer:

Using Text editor (XML view):

The name must match a method name that has a (View v) parameter, or it won’t work.

Now you should be able to run the app and see if the Button changes the text of your TextView.