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
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
How to Add Widget of an Android Application?
Next article icon

How to Create a Basic Widget of an Android App?

Last Updated : 16 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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, which are some of the Widgets available on the device. Widgets come along with the Application when you install it or download it from the Web. Generally, phones come with a manufacturing configuration but such elements can be adjusted by a user later in time.

In this article, we demonstrate how one can implement a basic widget for an Android App.

Widgets_Android


Steps for Creating a Basic 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. We are implementing it for both Java and Kotlin languages.

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.


Create_Widget


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.


New_Widget


Step 3: Install and Run the Code

  • Install and Run the code on Android Virtual Device (AVD) or a personal device.
  • Open the widget section of the phone, lookup for a widget with the Application name, select it, bring it to the home screen.
  • Try changing the dimensions and we are done!

Output: Run On Emulator

What extra files are generated in this process?

During this selecting and deploying process, a few extra files are generated and minor changes are made to existing files as well. No programming is required for generating a basic widget and is only required if an application is to be embedded inside the widget, as discussed in the later parts of the article. Let us now explain the newly generated files the changes make to the existing ones, one by one.

1. NewAppWidget.kt

Where it's generated?


NewAppWidget



Java
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.widget.RemoteViews;  // Implementation of App Widget functionality. class NewAppWidget extends AppWidgetProvider {     @Override     public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)     {          // There may be multiple            // widgets active, so update         // all of them         for (int appWidgetId : appWidgetIds) {updateAppWidget(context, appWidgetManager, appWidgetId);         }     }      // Enter relevant functionality for     // when the first widget is created     @Override public void onEnabled(Context context)     {         super.onEnabled(context);     }      // Enter relevant functionality for     // when the last widget is disabled     @Override public void onDisabled(Context context)     {         super.onDisabled(context);     }      private void     updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId)     {         String widgetText = context.getString(R.string.appwidget_text);                // Construct the RemoteViews object         RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);         views.setTextViewText(R.id.appwidget_text, widgetText);          // Instruct the widget manager to update the widget         appWidgetManager.updateAppWidget(appWidgetId, views);     } } 
Kotlin
import android.appwidget.AppWidgetManager  import android.appwidget.AppWidgetProvider  import android.content.Context  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  ) {      val widgetText = context.getString(R.string.appwidget_text)      // Construct the RemoteViews object      val views = RemoteViews(context.packageName, R.layout.new_app_widget)      views.setTextViewText(R.id.appwidget_text, widgetText)       // Instruct the widget manager to update the widget      appWidgetManager.updateAppWidget(appWidgetId, views)  } 


2. new_app_widget.xml

Where it’s generated?

NewAppWidget_xml


XML
<RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:background="#09C"     android:padding="@dimen/widget_margin">       <TextView         android:id="@+id/appwidget_text"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerHorizontal="true"         android:layout_centerVertical="true"         android:layout_margin="8dp"         android:background="#09C"         android:contentDescription="@string/appwidget_text"         android:text="@string/appwidget_text"         android:textColor="#ffffff"         android:textSize="24sp"         android:textStyle="bold|italic" />   </RelativeLayout> 

3. dimens.xml

Where it’s generated?



dimensxml


XML
<?xml version="1.0" encoding="utf-8"?>  <resources>       <!--      Refer to App Widget Documentation for margin information      http://developer.android.com/guide/topics/appwidgets/index.html#CreatingLayout      -->     <dimen name="widget_margin">8dp</dimen>   </resources> 

4. new_app_widget_info.xml

Where it’s generated?


new_app_widget_info


XML
<?xml version="1.0" encoding="utf-8"?>  <appwidget-provider     xmlns:android="http://schemas.android.com/apk/res/android"     android:initialKeyguardLayout="@layout/new_app_widget"     android:initialLayout="@layout/new_app_widget"     android:minWidth="40dp"     android:minHeight="40dp"     android:previewImage="@drawable/example_appwidget_preview"     android:resizeMode="horizontal|vertical"     android:updatePeriodMillis="86400000"     android:widgetCategory="home_screen">  </appwidget-provider> 

5. Changes made to AndroidManifest.xml file

XML
<?xml version="1.0" encoding="utf-8"?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="org.geeksforgeeks.widget_basic">       <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@style/AppTheme">                   <!-- Receiver Element is Added to link the widget files to the Application -->             <receiver android:name=".NewAppWidget">              <intent-filter>                  <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />              </intent-filter>               <meta-data                 android:name="android.appwidget.provider"                 android:resource="@xml/new_app_widget_info" />          </receiver>          <!-- ----------------------------Until Here------------------------------------>                  <activity android:name=".MainActivity">              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                   <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>          </activity>      </application>   </manifest> 

Is Programming Still Required? If so, which part of the code is to be changed? (In Continuation)

Yes, Programming is still a requirement for creating widgets. Changes are made inside the NewAppWidget.kt which is a Kotlin class and its counterpart new_app_widget.xml file that displays the widget. Functionalities can be declared inside the update app widget function for the application operations and new_app_widget.xml for adding multiple elements to the widget's display. Since both the files are linked internally, altering one of them brings changes to another. 

Regarding implementing multiple Widgets 

There are no restrictions on the number of widgets that an app can have, however, it is advised to have a minimum number of widgets as possible as widgets are dynamically changing elements. There are update callbacks (refer to new_app_widget_info.xml file ), updatePeriodMillis is a parameter referring to which the application keeps updating the widget, meaning, the application thread to update the widget keeps running in the background, acquiring some part of the limited RAM.


Next Article
How to Add Widget of an Android Application?
author
aashaypawar
Improve
Article Tags :
  • Android
  • Kotlin Android
  • Android Projects
  • Java-Android

Similar Reads

  • How to Create a Basic Intro Slider of an Android App?
    When we download any app and use that app for the very first time. Then we will get to see the intro slider inside our app. With the help of this slider, we educate our users on how they can use that app and it tells in detail about the app. In this article, we will take a look at the implementation
    4 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 Add Widget of an Android Application?
    It's known that many of the android apps that have installed on the phone contain widgets. The most common examples are the Calendar and the Clock widget. So what are these Widgets? Widgets are just a mini-app that lives on the home screen and apart from small launcher icons that normally appear on
    8 min read
  • How to Create a Custom Intro Slider of an Android App?
    Intro Slider in many apps is mostly used to educate the users about the app, the features of the app, and the services that our app will provide to us. In this article, we will take a look at the implementation of Custom Intro Slider in our app. What we are going to build in this Article? We will be
    8 min read
  • How to Create a Voting Application in Android?
    In general, voting means comparing two or more entities on the basis of certain conditions. In this article, we will create a simple voting application that uses two different programming languages namely Java and Python, and ask the user to vote for their preferred language. A sample GIF is given b
    3 min read
  • How to Create Buttons Inside a Widget in Android?
    PrerequisitesHow 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 acco
    4 min read
  • How to Create a Wallpaper App in Android Studio?
    Almost all Android devices are having a wallpaper set on their home screen. For setting this wallpaper to the screen many Android devices provides a Wallpaper Application where we can browse different types of wallpapers based on various categories. In this article we will look at, building a simila
    15+ min read
  • How to Build a QR Code Android App using Firebase?
    QR (Quick Response) code is a type of two-dimensional barcode that contains information encoded in a pattern of black and white squares. It was first developed in 1994 by a company named Denso Wave. Qr codes can be scanned by a smartphone or a dedicated QR code scanner, which uses the device's camer
    6 min read
  • How to Create a Quiz App In Android?
    Android is an operating system which is basically made for Mobile phones. It is based on the Linux Kernel and other open-source software and is developed by Google. Android is very popular nowadays among students and students are now choosing Android for their projects. It's very much important for
    7 min read
  • How to Create a Paint Application in Android?
    We all have once used the MS-Paint in our childhood, and when the system was shifted from desks to our palms, we started doodling on Instagram Stories, Hike, WhatsApp, and many more such apps. But have you ever thought about how these functionalities were brought to life? So, In this article, we wil
    8 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