Book Image

Android 9 Development Cookbook - Third Edition

By : Rick Boyer
Book Image

Android 9 Development Cookbook - Third Edition

By: Rick Boyer

Overview of this book

The Android OS has the largest installation base of any operating system in the world. There has never been a better time to learn Android development to write your own applications, or to make your own contributions to the open source community! With this extensively updated cookbook, you'll find solutions for working with the user interfaces, multitouch gestures, location awareness, web services, and device features such as the phone, camera, and accelerometer. You also get useful steps on packaging your app for the Android Market. Each recipe provides a clear solution and sample code you can use in your project from the outset. Whether you are writing your first app or your hundredth, this is a book that you will come back to time and time again, with its many tips and tricks on the rich features of Android Pie.
Table of Contents (24 chapters)
Title Page
Copyright and Credits
Dedication
About Packt
Contributors
Preface
Index

Creating a widget at runtime


As mentioned before, generally, the UI is declared in XML files and then modified during runtime through the Java code. It is possible to create the UI completely in Java code, though for a complex layout, it would generally not be considered best practice.

In this recipe, we are going to add a view to the existing layout defined in activity_main.xml.

Getting ready

Create a new project in Android Studio and call it RuntimeWidget. Select the Empty Activity option when prompted for the Activity Type.

How to do it...

We will start by adding an ID attribute to the existing layout so we can access the layout in code. Once we have a reference to the layout in code, we can add new views to the existing layout. Here are the steps:

  1. Openres/layout/activity_main.xml and add an ID attribute to the root ConstraintLayout, as follows:
android:id="@+id/layout" 
  1. Completely remove the default <TextView> element.
  2. Open the MainActivity.java file so we can add code to the onCreate(...