Basic Widget of an Android App

A widget is a version of an application that displays some functionalities of the application that is displayed on the lock screen and Home screens. For example, we see Weather, TIme, etc on the home screen. 

 


Step 1: Create a basic widget on Android Studio.


Step 2: Create a project or you can use an already created project. You can use any language, Java or Kotlin.


Step 3: Right-click on your project packager -> new -> widget ->app widget.

 

Step 4: The next step is to change the Class name, Placement, resizable, and press Finish, etc.

 

Step 5: Automatically create appWidget.java or kt file in your project.

import android.appwidget.AppWidgetManager

import android.appwidget.AppWidgetProvider

import android.content.Context

import android.widget.RemoteViews

 

class NewAppWidget : AppWidgetProvider() {

override fun onUpdate(

context: Context,

appWidgetManager: AppWidgetManager,

appWidgetIds: IntArray

) {

// There may be multiple widgets 

 (appWidgetId in appWidgetIds) {

updateAppWidget(context, appWidgetManager, appWidgetId)}}

// when the first widget is created

override fun onEnabled(context: Context) {}

// 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)val views =           RemoteViews(context.packageName, R.layout.new_app_widget)

views.setTextViewText(R.id.appwidget_text, widgetText)

appWidgetManager.updateAppWidget(appWidgetId, views)

}

Step 6: Automatically create nameofifle.xml file in your layout folder.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

style="@style/Widget.MyApplication.AppWidget.Container"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:theme="@style/Theme.MyApplication.AppWidgetContainer">

 

<TextView

android:id="@+id/appwidget_text"

style="@style/Widget.MyApplication.AppWidget.InnerView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:layout_margin="8dp"

android:contentDescription="@string/appwidget_text"

android:text="@string/appwidget_text"

android:textSize="24sp"

android:textStyle="bold|italic" />

</RelativeLayout>

 

Step 7: Below is the design of the widget view.

 

Step 8: Final output below.

 


Happy coding!

365Bloggy May 9, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive