A Widget is a mini version of an Application, that provides a ground for the user to navigate through it or use its features from the Home Screen or Lock Screen. Widgets contain elements according to the features it provides. Widgets, as previously termed a mini version of the Application, is capable of displaying similar elements that of an Application, through this article, let’s demonstrate the implementation of Buttons and correspondingly how they can be used for certain functionalities. Here is a preview of the same:
Steps for Creating Buttons Inside a Widget
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add the App Widget to the Project
- Right-Click on the app, move the cursor to new, find the “Widget” option at the end, select it.
- Specify the required properties for the widget such as min.width and height, config file and preferred language, etc, and proceed. Files are automatically generated.
Step 3: What to program? Where to program?
- In our application, since we wish to display two Buttons named “Activity1” & “Activity2“, we need to declare them inside the new_app_widget.xml file which is inside the Layouts in the Resources folder.
- The entire programming (back-end) is done in the newly created NewAppWidget.kt, Kotlin Class File in the Main Source Folder. Here, we construct the Buttons. Since these Buttons will redirect the users to different activities, we need to create two Empty Activities, we name them “Activity1” and “Activity2” respectively.
- These Activities serve as Pending Intents since they initialize only when the user clicks on one of the buttons.
- Changes are made to Activity 1 and Activity 2 front-end files to represent their names.
- Just refer to the below codes and the corresponding comments given below.
- new_app_widget.xml and NewAppWidget.kt files
- activity_1.xml, Activity1.kt, activity_2.xml, Activity2.kt files
In both, the XML files add only a TextView, and in the Kotlin files, we have added nothing. The users may write their own code as their requirements inside those files.
- activity_main.xml, MainActivity.kt files
There is nothing to do inside the activity_main.xml, MainActivity.kt files. The users may write their own code as their requirements inside those files.