Creating a widget for your desktop. Writing a Windows Sidebar gadget from scratch Create widgets




Today we will figure out how to create your own widget on an Android device. A widget is a familiar desktop element with which you can access some functions of an application: view news in the widget window, weather forecast, update news on various services, control various functions of the device (lock the screen, turn on the radio, Internet and many many others). This time we will not create something grandiose and very useful, like a flashlight :), but will make a simple widget that will be implemented in the form of a button, when clicked on, we, using a standard browser, will be taken to everyone’s favorite site. Of course, you can customize any website you want.

Create a new project, select Blank Activity, minimum version Android 2.2+. When creating a widget, the first thing to do is create an object AppWidgetProviderInfo, in which we will specify the xml file from which the view of the widget itself will be filled. To do this, create a folder in the project res/xml and in it we create a new xml file named widget.xml with the following content:

< appwidget- provider xmlns: android= android: minWidth= "146dp" android: updatePeriodMillis= "0" android: minHeight= "146dp" android: initialLayout= "@layout/activity_main" > < / appwidget- provider>

Now let's go to the file activity_main.xml and create the interface of our widget, it will consist of a button Button:

< LinearLayout xmlns: android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" android: layout_width= "match_parent" android: layout_height= "match_parent" android: gravity= "top" tools: context= ".MainActivity" >< Button android: id= "@+id/button" android: layout_width= "wrap_content" android: layout_height= "wrap_content" android: layout_marginLeft= "5dp" android: text= "@string/app_name" / > < / LinearLayout >

As you can see, we have created a regular button, and this will be our widget:

That is, you can then do whatever you want instead of this button.

Let's move on to working with the code in the file MainActivity.java. It must inherit from the class AppWidgetProvider, for which its main method exists onUpdate(). In this method we need to define two objects: PendingIntent And RemoteViews. At the end of their use, you need to call the method updateAppWidget(). File code MainActivity.java:

import android.net.Uri ; import android.app.PendingIntent ; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context ; import android.content.Intent ; import android.widget.RemoteViews ; import android.widget.Toast ; import com.example.widget.R ; public class MainActivity extends AppWidgetProvider( @Override public void onUpdate (Context context, AppWidgetManager appWidgetManager, int appWidgetIds) ( for (int i= 0; i< appWidgetIds. length; i++ ){ int currentWidgetId = appWidgetIds[i]; //Make a simple http request to the specified link and follow it: String url = "http://site" ; Intent intent = new Intent(Intent . ACTION_VIEW); intent. addFlags(Intent . FLAG_ACTIVITY_NEW_TASK); intent. setData(Uri . parse(url)); //We define two required objects of the class PendingIntent and RemoteViews: PendingIntent pending = PendingIntent . getActivity(context, 0 ,intent, 0 ); RemoteViews views = new RemoteViews(context. getPackageName(),R. layout. activity_main); //Configure the processing of a click to add a widget: views. setOnClickPendingIntent(R . id. button, pending); appWidgetManager. updateAppWidget(currentWidgetId,views); Toast. makeText(context, "Widget added", Toast . LENGTH_SHORT). show(); ) ) )

For our widget to work successfully, we need a little magic in the manifest file AndroidManifest.xml. It should look like this:

< manifest xmlns: android= "http://schemas.android.com/apk/res/android" package ="com.example.widget" android: versionCode="1" android: versionName="1.0" >< uses- permission android: name= "android.permission.INTERNET" / > < application android: allowBackup= "true" android: icon= "@drawable/ic_launcher" android: label= "@string/app_name" android: theme= "@style/AppTheme" > < receiver android: name= "home.study.MainActivity" > < intent- filter> < action android: name= "android.appwidget.action.APPWIDGET_UPDATE" / > < / intent- filter> < meta- data android: name= "android.appwidget.provider" android: resource= "@xml/widget" / > < / receiver> < / application> < / manifest>

As you guessed, the widget is defined in the tag<receiver> .

The only thing left to fix is ​​to edit the file strings.xml, adding the lines we used there:

< ? xml version= "1.0" encoding= "utf-8" ? > < resources> < string name= "app_name" >LEARN. ANDROID < string name= "action_settings" >Settings < string name= "hello_world" >Hello world!< / string> < / resources>

Attention! Android Studio may swear at you when you start the program, requiring you to specify a default activity. Select the line “Do not launch Activity”:

Now install the application on the emulator or device, add the widget to the desktop:

And click on it:


As you can see, everything works great.

So, in this tutorial we have created a simple Android Widget, consisting of a Button, when you click on our widget, we create a simple http request and follow the given URL link. You can practice with some other elements, not a button, and come up with interesting functionality for them. Good luck!

In order to make a widget in Android It is not at all necessary to know how to program. There are several design applications that make it easy to draw a widget and give it the desired functionality.

Minimalistic Text

The application allows you to create minimalistic widgets consisting of text and numbers. Despite the name, these widgets have very wide capabilities.

After installation, add a Minimalistic Text widget of the required size to your desktop. The widget settings window will open.

In the settings you can select the background, orientation, font, click action, etc. Also in the settings there are predefined layouts for filling:

  • Time.
  • Date of.
  • Charge level.
  • Temperature.

Additional options for filling the widget are available when creating your own widget layout:

  • Text.
  • Free/used space on the SD card.
  • System operating time.
  • The amount of data transferred over the mobile network and more.
  • Name of the Wi-Fi network, IP address in the Wi-Fi network.
  • Amount of used RAM.

All values ​​can be displayed in text and in numbers.

Ultimate custom widget (UCCW)

This application allows you to make widgets not only from text, but also with graphic content.

When launched, the widget creation window opens. To add an object to the widget, click the +/- button at the top. To move and edit it in any way, click on the “Select Object” button at the top and select the added object.

You can place the following objects on widgets:

  • Time, date and day of the week.
  • Analog clock.
  • Custom text.
  • The charge level in numbers or a graphical display of it.
  • All weather information - temperature, humidity, wind speed, etc.
  • Geometric figures.
  • Images.
  • Number of unread Gmail emails, sms and missed calls.
  • The time when the alarm clock will ring.

Each element can be rotated, stretched, bent and its color changed. Of course, you can configure the click action (Select Object->Hotspots). Import and export of created widgets is supported.

The Android operating system has many functions and capabilities. One of them is widgets - windows that allow you to use part of the functionality of the application without launching it.

Basically, widgets come bundled with the application. However, there are programs that do not have this option. This means you need to take matters into your own hands!

  • Using the Play Market, we download the free application “KWGT Kustom Widget Maker”, which can be purchased for free, but some functions will be available only after purchasing the add-on.

The program acts as a platform for launching third-party widgets from different developers. In addition, you can change the appearance of widgets and give them additional functionality.


At first, you might think that “KWGT Kustom Widget Maker” is a complex application that resembles software development programs. Yes and no: the interface is similar, but there is nothing complicated here.


To start editing widgets:

  • go to the desktop and call up the menu for editing desktops by holding the menu button or long tapping on the screen;
  • find the “KWGT” widget frame and set the required size, for example - 4x2. After this, a window appears on the desktop;
  • Click on the window, thereby opening the widget selection menu;
  • Select the layout you like and click on it (Additional layouts can be downloaded from the Play Store. To do this, specify “KWGT widgets” in the application search bar);
  • After selecting the layout you like, the application will proceed to edit it. The following settings will be available:
  1. Elements responsible for setting the geometric parameters of the widget;
  2. Background, responsible for the background image on the widget;
  3. A touch that specifies the actions that will be performed when the widget is activated;
  4. The layer responsible for the scale of the widget;

As a result, we will get a unique widget with the necessary functionality.

Recently I needed to create a gadget for Windows Sidebar. I didn’t have any skills in this, so after googling a little and reading the documentation, let’s get started.

I'll show you what I ended up with right away.


The gadget will receive information from the site in xml form, parse it and, in fact, display it. The gadget will also check for new versions, and if they are present, refuse to work :)
Initially, for the sake of gaining experience, I wanted to write a gadget entirely in VBScript (since I had not dealt with it yet), but in the end I had to make inserts in JavaScript.
Let's move directly to the code. I will not review the entire code here, I will only show the main points. The link to the finished gadget is at the end of the article.
The main file of a gadget is its manifest - the Gadget.xml file. It should be called exactly that and located in the root of our archive (the gadget is nothing more than a ZIP archive with the .gadget extension).

Weather from Info.Denms.Ru 1.0.1232 Full Weather Widget (Info.Denms.Ru)

Let's look at it in more detail.
Element must contain apiVersion equal to 1.0.0 (at the moment), as well as the src attribute, which specifies the main file of our gadget;
Permissions for the gadget. Set equal to full;
Minimum version of Windows Sidebar. Currently – 1.0;
Options - gadget name, - version, - information about the author, - link to the page with the gadget, - gadget icon and will be displayed on the panel of installed gadgets.

The main.html file is an ordinary html file, I will not list it in full, I will only dwell on some points.
The g:background element is used to set the background of the gadget. Let's make it transparent.

The gadget can be in two states – docked (on the left in the screenshot above), and undocked (on the right). We will store the current state of the gadget in the JavaScript docked variable.

We will need the isDocked wrapper function in the future to find out the current state of the gadget from VBScript (no matter how hard I tried, I couldn’t implement this in pure VBScript). One more note - the scripts work correctly in this order, i.e. First we describe VBScript scripts, then JavaScript.

The remaining elements in main.html are absolutely positioned DIV elements. Subsequently, from scripts we will access them by their id.

Using JavaScript, we will set the docked and undocked states for the gadget, and also specify the settings file (main.js)

System.Gadget.onDock = resize; System.Gadget.onUndock = resize; System.Gadget.settingsUI = "settings.html"; System.Gadget.onSettingsClosed = SettingsClosed; docked=0; //initial state of the gadget resize(); //initialization

As you can see from the listing above, when the gadget states change, the resize() function will be called.

Function resize() ( bd = document.body.style; System.Gadget.beginTransition(); if (System.Gadget.docked) ( // small state bd.width=148; // set the gadget size bd.height=201 ; docked = 1; bd.background="url(images/gadget.png) no-repeat"; //set the background //then follows the transfer of values ​​from the undocked state to docked and zeroing the elements for the undocked state document.getElementById("small_needupdate ").innerHTML = document.getElementById("big_needupdate").innerHTML; document.getElementById("big_needupdate").innerHTML = ""; //... ) else ( // big state bd.width=230; bd. height=160; bd.background="url(images/gadgeth.png) no-repeat"; docked=0; //transfer values ​​from docked to undocked and reset elements for docked state document.getElementById("big_needupdate"). innerHTML = document.getElementById("small_needupdate").innerHTML; document.getElementById("small_needupdate").innerHTML = ""; //... ) System.Gadget.endTransition(System.Gadget.TransitionType.morph,1); )

You can also describe the function of saving settings. My gadget doesn’t have them, but as an example I’ll show you how it’s done.

Function SettingsClosed(event) ( if (event.closeAction == event.Action.commit) ( //alert System.Gadget.Settings.readString("test"); ) )

ReadString – reads a previously saved string, writeString, respectively, writes.
Methods System.Gadget.beginTransition(); and System.Gadget.endTransition(); needed for “smooth” resizing of the gadget. They are ignored in Windows Seven, but I still left them for backward compatibility.

As mentioned above, the server provides us with weather information in xml format.

1.7 41 cloudy snow 87 South-West 5 -3 -1 -1 26 1 -9 41 0 …

We will download and parse xml using VBScript.

Sub DownloadXML2 Set objXML = CreateObject("Microsoft.XmlHttp") objXML.Open "GET", "http://info.kovonet.ru/weather.xml", True objXML.OnReadyStateChange = GetRef("objXML_onreadystatechange") objXML.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" objXML.Send iTimeoutID = window.SetTimeout("mySleep", 1000) End Sub

The mySleep function will check our connection for a timeout.

Sub mySleep if bRespReceived = "false" then "response not yet received iTimeout = iTimeout + 1 if (iTimeout > 30) then "timeout timerFirstRun = window.SetTimeout("Update", 60000) "attempt to re-update in a minute else "timeout yet not reached, continue to count seconds iTimeoutID = window.SetTimeout("mySleep", 1000) end if end if End Sub

If the download is successful, objXML.readyState will be equal to four, and status (objXML.status) will return the value 200.

Function objXML_onreadystatechange() If (objXML.readyState = 4) Then "msgbox objXML.statusText If (objXML.status = 200) Then bRespReceived=true SaveFile(objXML.responseText) else timerFirstRun = window.SetTimeout("Update", 60000) " attempt to update again in a minute End If End If End Function

In this case, save the file to a temporary Windows folder

Function SaveFile(what) Set fso = CreateObject("Scripting.FileSystemObject") tempFolder = fso.GetSpecialFolder(2) filepath = tempFolder+"\weather.xml" Dim fso1, tf Set fso1 = CreateObject("Scripting.FileSystemObject") Set tf = fso1.CreateTextFile(filepath, True, True) "rewrite, unicode tf.Write(what) tf.Close ParseXML End Function

And we begin to parse the file.

Sub ParseXML Set fso = CreateObject("Scripting.FileSystemObject") tempFolder = fso.GetSpecialFolder(2) filepath = tempFolder+"\weather.xml" Set xmlDoc = CreateObject("Msxml2.DOMDocument") xmlDoc.async="false" xmlDoc. load(filepath) "main node – in our case Set currNode = xmlDoc.documentElement "days of the week – Set dayNode = currNode.firstChild While Not dayNode Is Nothing Set currNode = dayNode.firstChild While Not currNode Is Nothing if currNode.parentNode.getAttribute("id") = "today" then "today if currNode.nodeName = "temp" then document.getElementById(prefix+"maintemp").innerHTML = currNode.childNodes(0).text+Chr(176) "display the remaining elements Else "not today, display more finely"... end If Set currNode = currNode.nextSibling Wend Set dayNode = dayNode.nextSibling Wend End Sub

Checking for new versions is done in exactly the same way.
Don't forget to create a settings file - settings.html, the existence of which we announced above.

Settings

That's all, actually. I would be glad if my (first :)) article was useful to someone.

Used sources.

Create WordPress widget– this is approximately how to create a plugin, but much simpler and clearer. All you need is one file with everything PHP code that is much easier to write than a plugin that has several files. There are three main functions of the widget: these are widget, update And form.

  • function widget()
  • function update()
  • function form()

| Download sources |

Basic structure

The basic design of our widget is very simple, there are useful functions that you need to know. The backbone of our widget structure will be something like this:

Add_action("widgets_init", "register_my_widget"); // function to load my widget function register_my_widget() () // function to register my widget class My_Widget extends WP_Widget () () // The example widget class function My_Widget() () // Widget Settings function widget() () // display the widget function update() () // update the widget function form() () // and of course the form for the widget options

Step 1. widget_init

Before we do all this, we need to load our widget using the function widget_init. This is a clue to action, which you can find more information about in the WordPress codex.

Add_action("widgets_init", "register_my_widget");

The next thing we will do is let's register our widget in WordPress so that it is available in the widgets section.

Function register_my_widget() ( register_widget("My_Widget"); )

Step 2. Class

We will enclose our widget in Class. The class name matters! What we have to keep in mind is that the class name and function name must be identical.

Class My_Widget extends WP_Widget()

Now we will pass some options settings. For example, we can send width And height. We can also give a small description to our widget if we want. This will be useful if you associate the widget with your commercial theme.

Function My_Widget() ( function My_Widget() ( $widget_ops = array("classname" => "example", "description" => __("A widget that displays the authors name ", "example")); $control_ops = array("width" => 300, "height" => 350, "id_base" => "example-widget"); $this->WP_Widget("example-widget", __("Example Widget", "example" ), $widget_ops, $control_ops);

Now that we're done with the basic requirements for our widget, we'll turn our attention to three functions, which we talked about earlier and which are important functions or basic blocks for building our widget!

Step 3: function widget()

The first function refers to display our widget. We'll pass on a few arguments into our function. We will pass arguments from the topic, this could be a title or some other parameters. Now we pass the variable instance, which is associated with the class of our function.

Function widget($args, $instance)

After this we extract options from arguments because we need the parameters to be available locally. If you don't know what a local variable is, don't worry about it now and just add this step.

extract($args);

Next we will install title And other parameters for our widget, which can be changed by the user in the widget menu. We also add special variables like $before_widget, $after_widget. These parameters are processed by the theme.

$title = apply_filters("widget_title", $instance["title"]); $name = $instance["name"]; $show_info = isset($instance["show_info"]) ? $instance["show_info"] : false; echo $before_widget; // Display the widget title if ($title) echo $before_title . $title . $after_title; //Display the name if ($name) printf("

" . __("Hey their Sailor! My name is %1$s.", "example") . "

", $name); if ($show_info) printf($name); echo $after_widget;

Step 4: function update()

Function update($new_instance, $old_instance) ( $instance = $old_instance; //Strip tags from title and name to remove HTML $instance["title"] = strip_tags($new_instance["title"]); $instance[" name"] = strip_tags($new_instance["name"]); $instance["show_info"] = $new_instance["show_info"]; return $instance; )

One thing to note: here we are using strip_tags to remove all text from XHTML, which may disrupt the operation of our widget.

Step 5. function form()

In the next step we will create form which will serve input block. It will accept user-defined settings and values. Function form may include checkboxes, text input fields, etc.

Before we create these input fields, we need to decide what to show when the user doesn't select anything from the widget. To do this, we will pass default values ​​for the parameters, such as title, description, etc.

//Set up some default widget settings. $defaults = array("title" => __("Example", "example"), "name" => __("Bilal Shaheen", "example"), "show_info" => true); $instance = wp_parse_args((array) $instance, $defaults); ?>

Now we will create text input field. We'll wrap these values ​​in a paragraph tag.

// Widget Title: Text Input

" name="get_field_name("title"); ?>" value="" style="width:100%;" />

//Text Input

" name="get_field_name("name"); ?>" value="" style="width:100%;" />

// Checkbox

id="get_field_id("show_info"); ?>" name="get_field_name("show_info"); ?>" />

Conclusion

OK it's all over Now. You've just made a cute and simple widget yourself that displays the blog author's name. Moreover, it allows the user to choose whether to show the information to the audience or not. Save the code in PHP file and upload it to your theme folder. Call him in your functions.php. After that, go to the console in Appearance → Widgets and you will see your widget.

All of this code is included in the file attached to the article, making it even easier to copy and paste. Enjoy!