- How to create widgets in android
- tashariko/widget_sample
- widget_sample — tutorial to how to create a widget
- Introduction to widgets
- App Widgets | Android Developers
- App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and…
- Create a widget of 1*1 dimension
- Add the click listener
- PendingIntent | Android Developers
- By giving a PendingIntent to another application, you are granting it the right to perform the operation you have…
- Adding multiple widgets for your app
- Update the Data/UI for widget
- Handling adapters for widget
- Making an Android Widget
How to create widgets in android
Aug 26, 2017 · 12 min read
This article will guide you through the complete process of widget creation. We will do this in steps:
- Introduction to widgets
- Create a widget of 1*1 dimension: we will add the basic files to the project that is needed to create a widget.
- Add the click listener: we will see here that how the click listener works and how it is different from the normal click listener.
- Adding multiple widgets for your app: We will see how to different widgets to the widget provider.
- Update the Data/UI for widget: We will detect the size of the widget and then accordingly change the data/UI for the widget.
- Handling adapters for widget: We will see how to add Gridview/Listview/Stackview on the widget.
I have created a sample project to guide you through this tutorial for creating the widget. you can take the pull from here.
tashariko/widget_sample
widget_sample — tutorial to how to create a widget
Here i have created branches for all the steps required. I think this project is going to be sufficient to get the idea on how to create a widget in android. ok then, let’s get started.
Introduction to widgets
Widget is the part of our android application, which stays outside the app. It operates in a different process than our application. These are treated as a separate app that works on homescreen. So instead of using normal Views that we use in our application, android uses Remote Views. Remote views seems just like any other xml views that we use in app creation, but with minor changes.
For example, this is the layout file for our widget, for now it just shows an image.
Although they seems similar to normal views they have some limitations on what they can support. They normally support all the popular basic views, but views like constraint layout and recycler views are not supported, to see the full list of supported views you can refer to :
App Widgets | Android Developers
App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and…
Now, to access the views in java file we use findViewById(). But here we have methods like setTextViewText() to add text to the textview.
Now lets start with adding a widget to our homescreen.
Create a widget of 1*1 dimension
We are going to place a widget on the homescreen, for now it will show a icon there. This icon will be of 1*1 dimension.
Switch to branch step_1-basic_widget_creation.
At first we need to add a file at res/xml. i am calling this file sample_widget_info.xml. It consist of “ appwidget-provider” which gives the basic information regarding our widget. It is as follows:
- According to the above image, to create a widget of 1*1 dimension we need the minWidth and minHeight of 40dp respectively.
- initialLayout attribute decides which view to use initially when we add the widget to the homescreen.
- preview_image attribute decides what icon/image to show in the widget selector. Here as our selection of dimension, the icon is shows as 1*1 widget.
- resizeMode attribute defines if we want the widget to be able to expand horizontally or vertically.
- updatePeriodMillis attribute defines when time interval to update the widget. the minimum time we can give is 30 minutes i.e. 1800000.
- widgetCategory attribute defines where to put the widget homescreen or keyboard.
Now we have to tell android that we have added the widget for our app and we do this by defining a receiver in the manifest file. This receiver will extend AppWidgetProvider , here that file is SampleAppWidgetProvider.
We will add this receiver in the manifest file.
Here we added the action to detect:
- An new instance of Your AppWidget added to Home Screen from AppWidget Chooser( from AppWidget provider) is added.
- When requested update interval having lapsed which you have provided in AppWidget info file using android:updatePeriodMillis attribute.
- When device reboot
The meta-data points to the info file we created for our widget.
Now if all has gone correctly, after installing the app, you can see the widget option in the widget provider in your mobile. just drag it on the homescreen and you can see it.
Add the click listener
Now we want to open an activity when we click on that widget. Here the click implementation is a little different than the normal click listener. We are using pending intent to open an activity here. Pending intent is used here because by this we can declare an Intent and and execute it on the click of the widget, same as we use it for notifications.
To learn more about Pending Intent go to:
PendingIntent | Android Developers
By giving a PendingIntent to another application, you are granting it the right to perform the operation you have…
Now switch to the branch step_2-widget_click_implementation.
For implement the click, we are now going to use file SampleAppWidgetProvider. Here we are only going to use onUpdate() method. This method get called whenever there is a chance that the widget gets updated (not the widgets dimensions or options, more on this later).
It provides following parameters:
- Context : To provide us the context. gets information about installed AppWidget providers and other AppWidget related state.
- AppWidgetManager : Gives information about installed AppWidgets providers and other AppWidget related state.
- int[] : This is an array of appWidgetIds, these ids represents all the AppWidgets that are available on the homescreen for our app.
Now, we are going to add a for loop in onUpdate() method to access all the widgets that are available on the homescreen for our app.
Here updateAppWidget() method will handle the Remote Views work. For now we only want to open an activity nothing more. so our updateAppWidget() method will look like this:
Here we did 3 things:
- Created a pending intent to open MainActivity.
- Constructed a Remote View and added the click listener via the method setOnClickPendingIntent().
- Instruct the widget to update the widget, we will call this method everytime we update the widget.
All is done, now try it yourself, now if you click on the icon in the app widget, then you can open an activity.
Ok, now lets go a step further, and we will add 2 images in the widget and we will open different activities on each click. If you have issue regarding that, switch the branch to
Switch to the branch step_2-widget_multi_click_implementation
Adding multiple widgets for your app
We added a single widget to home screen, now what if you want one widget to open an activity like we did before and another widget to show the list on homescreen. Suppose you need these 2 widgets,
Now for this you need 2 types of views.
There are two ways to do it.
- We can use one xml file and one AppWidgetProvider and detect the change in dimension when you increase or decrease the size and refresh the view to show the new view and handle accordingly. But in this case in the Widget provider you will only see one widget with the dimension you define in the info file sample_widget_info.xml.
- We can use 2 xml file and 2 AppWidgetProvider for these 2 widgets. The plus point here is that we will be seeing 2 widgets in the Widget Provider but here we cant change the size of the 2 widgets below the minimum dimensions we provide. Here we will try this step and we will look into the first one afterwards.
Switch to the branch step_3-multiple_widget.
Lets create a second info file white_sample_widget_info.xml, second AppWidgetProvider file SampleWhiteAppWidgetProvider.java and second layout file layout_widget_white_simple.xml. If you have any problem then refer to the code in the above mentioned branch.
Now we will implement the first method to show multiple view in single widget.
Switch to the branch step_3-multiple_view_single_widget
Here we have 2 views but one AppWidgetProvider.
Now this method is a little tricky one, as mentioned above in step 3 the onUpdate() method don’t get called when you change the dimension of the widget, instead onAppWidgetOptionsChanged() methods gets called. So instead of calling the update method to get the Remote View, we are going to use a service which will notify that the view is updated and via that we w will refresh the widget. The service is going to be an Intent Service WidgetUpdateService.java.
This service is triggered from 2 places, from onUpdate() method and from onAppWidgetOptionsChanged(). Now we are going to create a Remote View object from that service, We did this because we want to detect the change in dimensions of the widget and it cant be done from onUpdate() method. So the 2 methods in our SampleAppWidgetProvider.java will look like this:
In startActionUpdateAppWidgets() method we are starting the service as
We will handle ACTION_UPDATE_APP_WIDGETS action in onHandleIntent() method. Here we are going to get an instance of AppWidgetManager and via this we are going to call the update method updateAppAllWidget() of SampleAppWidgetProvider.java class to get the Remote View. We will do this as:
And the updateAppAllWidget() now handles the updation of all the widgets on the screen(the work we were doing in onUpdate() is done here). It looks like this:
Now we want to detect the change in dimension of the widget, we do this as:
As you can see, to get the width we use the method getAppWidgetOptions (). This method can be used to any other option also. So to get the minimum width of the widget i used the code:
So we are providing the updateAppWidget() remote view according to our need. By the table I mentioned above for dimensions, I put the check of widget width less than 300 to occupy minimum of 4 blocks of homescreen. If width is less than 300, i want to show the smaller layout else the larger view of the widget.
One thing to notice, I used 300 as my mark if I want the size of the widget less than 4*1. It came from that table only, but to remember it easily I use multiple of 100. For most cases this will work.
Update the Data/UI for widget
It will be going to be same as above with minor changes, just to make this this updating concept clear.
Switch to the branch step_4-update_view_by_height.
Suppose you want to show a text at the top of widget if the height of the widget is increased. If height of the widget is greater than 100, we will show the text.
Here we use the PendingIntent flag FLAG_UPDATE_CURRENT because we wanted to update the current state of the MainActivity.
Handling adapters for widget
These are all simple views we used to show on the widget, what if we want to show a Collection View(listview or a gridview or a stackview).StackView is the image view we see for some apps. eg. Android Authority app) All uses the same concept so i am going to use a listview here.
As normal Listview for widget, we need the adapter here, but the normal adapter will not work here, instead we are going to start a service which will trigger the adapter and handle our listview.
Switch to the branch step_5-widget_list_view.
Few things to notice here:
- we will use setRemoteAdapter() method to attach the adapter to our ListView. You can see this in our WidgetProvider.
- It will start the RemoteViewsService service which trigger, the RemoteViewsService.RemoteViewsFactory. Its an interface for an adapter between a remote collection view, in our case for ListView. You can see this in ListViewWidgetService.
- We are detecting the change in the size of the widget in onAppWidgetOptionsChanged() and if width is greater than 300 we are starting the service.
In the service we are creating the data and saving it in sharedprefs. You can handle data however you want to handle. After that same process, get the instance of AppWidgetManager and call updateAllAppWidget().
Now in the adapter class AppWidgetListView. Mainly there are 2 important methods, getCount() to get the size of the list to show and getViewAt() to get the remote view of the specific position.
Now, we have to implement the click on the list item to do a task, here we are opening the activity with some data. In remoteView the click works differently on collection views. Implementing the click to each of the item is an expensive task, so we implement the click to the complete list view in the AppWidgetProvider.
Then we add the extra data for our click in the adapter we created in getViewAt. It is done by fillInIntent.
So after implementing the click, our getViewAt() method looks like this:
Now if you run the app, you can see the complete work with the click on the list item.
Источник
Making an Android Widget
Jan 11, 2019 · 4 min read
In this tutorial, you will learn how to create an Android Widget that is a homescreen memo and give it a custom typeface.
What is a widget?
Widgets are smaller views of an application that can be placed on the home screen for faster access.
Making a Widget
In the Android Studio menu, select File -> New -> Widget -> App Widget. This will open up a configuration screen.
- On this screen, name your widget MemoWidget under the Class Name prompt.
- Widgets can be placed on the home screen or the lock screen. However, it can only be placed on the lock screen (called keyguard) for Android versions lower than 5.0.
- Make your widget Not Resizable for a static memo size.
- Determine the size of your widget with the Minimum Width and Minimum Height prompts.
- Check Configuration Screen if you want a configuration activity for your widget. You will need to check this if you want to change the appearance of the widget based on user input. To follow this tutorial, check Configuration Screen, since we are displaying user inputted text on a memo.
When you select finish, five th i ngs will be created for you: a Java class for the widget, a Java class for the configuration activity, a xml layout for the widget, a xml layout for the configuration activity, and a xml file for the widget details.
Making the Widget Layout
Open the memo_widget.xml, which can be found under app -> res -> layout in the project menu.
Go to the text of the layout. We’re going to change the TextView to an ImageView and change some of the settings, as shown below:
The padding is necessary for the specific background image used because I wanted the text to begin not flush against the left side. If you want your text against the left side, remove the padding.
The background should be set to a drawable that you want to be the background of your memo.
Custom Typeface on Memo
To create a custom typeface, you must first create an assets folder under the app folder in the Project window. Next, in the assets folder, create a directory called fonts. Then copy paste the ttf file of your font into the fonts folder.
For widgets, the only way to use a custom typeface is to draw the text onto a canvas with a DynamicLayout.
Under the MemoWidget class, delete the view.setTextViewText(…) from the updateAppWidget method.
Create a private static DynamicLayout called textLayout. Create a string variable called widgetTextString, and set it to widgetText.toString. This will be used later as an argument for the creation of the DynamicLayout.
We will create a Bitmap for the canvas, the TextPaint, then a Typeface. Next we will set the TextPaint to our Typeface. AntiAlias must be true to smooth the text. We will also set the text size of the TextPaint. Initialize the textLayout using the user-inputted text and the textPaint we created.
We will create an x and y value for the canvas location. We will translate the canvas to those values, then draw the text onto the canvas. Finally we will set the ImageView to our bitmap.
When the code is run, you will have a working memo widget with a custom font!
Источник