Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Center a Button in a Linear Layout in Android?
Next article icon

How to Create Buttons Inside a Widget in Android?

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites

  • How to Create a Basic Widget of an Android App?
  • How to Create a Dynamic Widget of an Android App?

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 provide. 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:

https://media.geeksforgeeks.org/wp-content/uploads/20240801003610/buttoninsidewidget.mp4

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, and select it.
Screen-Shot-2020-08-29-at-1

Add the App Widget to the Project

  • 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.
Screen-Shot-2020-08-29-at-2

Specify the required properties


Step 3: What to program? Where to program?

  1. 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.
  2. 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.
  3. These Activities serve as Pending Intents since they initialize only when the user clicks on one of the buttons.
  4. Changes are made to Activity 1 and Activity 2 front-end files to represent their names.
  5. Just refer to the below codes and the corresponding comments given below.
  • new_app_widget.xml and NewAppWidget.kt files
XML
<RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:background="#0F9D58"     android:padding="@dimen/widget_margin">      <!-- Button 1 -->     <Button         android:id="@+id/btn1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Activity1"         android:layout_centerInParent="true"         />        <!-- Button 2 -->     <Button         android:id="@+id/btn2"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Activity2"         android:layout_centerHorizontal="true"         android:layout_below="@id/btn1"         />  </RelativeLayout> 
Kotlin
package org.geeksforgeeks.widget_buttons  import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.widget.RemoteViews   // Implementation of App Widget functionality class NewAppWidget : AppWidgetProvider() {     override fun onUpdate(         context: Context,         appWidgetManager: AppWidgetManager,         appWidgetIds: IntArray     ) {         // There may be multiple widgets active, so update all of them         for (appWidgetId in appWidgetIds) {             updateAppWidget(context, appWidgetManager, appWidgetId)         }     }      // Enter relevant functionality for when       // the first widget is created     override fun onEnabled(context: Context) {             }      // Enter relevant functionality for when       // the last widget is disabled     override fun onDisabled(context: Context) {             }  }  internal fun updateAppWidget(     context: Context,     appWidgetManager: AppWidgetManager,     appWidgetId: Int )   /////////////////////////////Start Coding Here/////////////////////////////////////// {      // Create a pending Intent for Activity 1     val i1 : PendingIntent = Intent(context,Activity1::class.java).let { intent ->         PendingIntent.getActivity(context, 0, intent, 0)  }      // Create a pending Intent for Activity 2     val i2 : PendingIntent = Intent(context,Activity2::class.java).let { intent ->         PendingIntent.getActivity(context, 0, intent, 0)  }      // Construct the RemoteViews object     val views = RemoteViews(context.packageName, R.layout.new_app_widget)         // Button 1 onClick Function         .apply{setOnClickPendingIntent(R.id.btn1,i1)}          // Button 2 onClick Function         .apply { setOnClickPendingIntent(R.id.btn2,i2) }       // Instruct the widget manager to update the widget     appWidgetManager.updateAppWidget(appWidgetId, views) } /////////////////////////////Code Ends Here/////////////////////////////////////// 
  • 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.

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".Activity1">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Activity 1"         android:layout_centerInParent="true"         />  </RelativeLayout> 
Kotlin
package org.geeksforgeeks.widget_buttons  import androidx.appcompat.app.AppCompatActivity import android.os.Bundle  class Activity1 : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_1)     } } 
XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".Activity2">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Activity 2"         android:layout_centerInParent="true"         />  </RelativeLayout> 
Kotlin
package org.geeksforgeeks.widget_buttons  import androidx.appcompat.app.AppCompatActivity import android.os.Bundle  class Activity2 : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_2)     } } 
  • 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.

XML
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Hello World!"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintLeft_toLeftOf="parent"         app:layout_constraintRight_toRightOf="parent"         app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout> 
Kotlin
package org.geeksforgeeks.widget_buttons  import androidx.appcompat.app.AppCompatActivity import android.os.Bundle  class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)     } } 

Output: Run on Emulator

https://media.geeksforgeeks.org/wp-content/uploads/20200907224522/Screen-Recording-2020-08-31-at-19.24.34.mp4


Next Article
How to Center a Button in a Linear Layout in Android?
author
aashaypawar
Improve
Article Tags :
  • Android
  • Kotlin
  • Android Projects

Similar Reads

  • How to Set Buttons Inside an Alert Dialog in Android?
    In this article, we are going to see how can we set two buttons inside an Alert Dialog. For example, we can see when an alert dialog is pop up then their two types of buttons available one is the Ok or Positive Button another one is Cancel or Negative Button. Alert dialogs are most frequently used i
    4 min read
  • How to Center a Button in a Linear Layout in Android?
    LinearLayout is a view group that aligns all children vertically or horizontally in a single direction. The "android:orientation" parameter allows you to define the layout direction. A button is a component of the user interface that can be tapped or clicked to carry out an action. Nowadays while de
    2 min read
  • How to Create a Basic Widget of an Android App?
    Widgets are the micro-version of the application that consists of some functionality of the application that is displayed only on the Home Screens or the Lock Screen. For example, we see Weather, Time, and Google Search Bars on the Home Screen, and FaceLock, and FingerprintLock on the Lock Screen, w
    5 min read
  • How to Add Share Button in Toolbar in Android?
    In this article, we are going to create a simple Share Button in the Toolbar in Android. The Share Button is used to share information on mail, Bluetooth, Facebook, Twitter, WhatsApp, etc to an individual person or a group on any social media. We can share any type of message like text, images, vide
    4 min read
  • How to Generate Dynamic Multiple Buttons in Android?
    In Android Studio, buttons are graphical user interface (GUI) elements that users can click or tap to perform an action. Buttons are typically represented by a rectangular or rounded rectangular shape with a label or an icon. In this article, we will learn to make dynamic multiple buttons in android
    3 min read
  • How to Create an ImageButton in Android?
    Nowadays, image buttons play a big role in making the android application more interactive and user-friendly. Be it any social media app like Instagram or Facebook or any shopping app or streaming app, each application uses this feature widely. In this article, we will take a look at the implementat
    3 min read
  • How to Create a Dynamic Widget of an Android App?
    Widgets are the UI elements provided by an application for accessing some of its features remotely either from Home Screens or Lock Screens. Widgets can be Static or Dynamic meaning that the display elements don't change (Static) or change (Dynamic) with time. Through this article, let's demonstrate
    3 min read
  • How to Save Switch Button State in Android?
    In Android, a Switch is a type of button that lets the user toggle between two actions or instances. In general, a Switch is used for selecting one between two options that can be invoking any actions or functions. In this article, we are going to see how we can save the state of the Switch Button i
    3 min read
  • How to Enable/Disable Button in Android?
    The Enable/Disable Feature is used in many Android apps so the basic use of that feature is to prevent the user from clicking on a button until they will add all the required fields that have been asked. We are considering an example of email and password if the user has entered the email and passwo
    3 min read
  • How to Change Button Font in Android?
    A Button in Android is a UI element provided to a user to click to perform a certain action. A text can be set inside the button to name it. However, this text can be seen in a particular font only which is set by default. So in this article, we will show you how you could change the Button text fon
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences