findViewById - How to Find a Button using ID

How to Find a Button using ID

findViewbyId was added in API Level 1

findViewById: Look for a child Button with the given id. If this view has a given id, return this Button.
The findViewById() method is available to all activities in Android. findViewById allows you to find a view inside an activity layout.

1. In the main.xml file, Name the Button, Name it myButton.

2. In the MainActivity.java file, Declare a Button named myButton.

3. Add the below code to the onCreate method. Where R.id.myButton is the same as the android:id name in your main.xml file, and myButton is the button name referred to in Java. This returns a Button View class and is casted to a Button type so you can work with it.

myButton = (Button) findViewById(R.id.myButton); 

4. Compile and run!

Next Recommended Article: android:onClick - Add an OnClick Action to a Button

Resources: