As you may have seen from previous recipes, widgets are declared in a layout file, or created in code. For this recipe, we will go step by step to add a button with the Android Studio Designer. (For later recipes, we will just show the layout XML.) After creating the button, we will create a method to receive the button click events using onClickListener()
.
Start a new project in Android Studio and call it InsertWidget
. Use the default options for creating a Phone and Tablet
project and select Empty Activity
when prompted for the Activity Type
. You can delete the default TextView
(or leave it) as it will not be needed for this recipe.
To insert a widget into a layout, follow these steps:
- Open the
activity_main.xml
file in Android Studio and click on theDesign
tab. As you can see, by default, Android Studio adds aTextView
to the layout. Select theTextView
and delete it: