How to Create Buttons Inside a Widget in Android?
Last Updated :
08 Aug, 2024
Prerequisites
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:
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.
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.
Specify the required properties
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
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
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 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
2 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