Android 简明教程

Android - Widgets

小组件是放置在主屏幕上安卓应用程序的一个小工具或控件。有了小组件,您可以将自己喜爱的应用程序放在主屏幕上,以便快速访问,因此小组件非常方便。您可能已经看到过一些常见的小组件,如音乐小组件、天气小组件、时钟小组件等。

A widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your home screen in order to quickly access them. You have probably seen some common widgets, such as music widget, weather widget, clock widget e.t.c

小组件可能类型繁多,诸如信息小组件、收集小组件、控制小组件和混合小组件。安卓为我们提供一个完整的框架来开发我们自己的小组件。

Widgets could be of many types such as information widgets, collection widgets, control widgets and hybrid widgets. Android provides us a complete framework to develop our own widgets.

Widget - XML file

要创建一个应用程序小组件,首先您需要的是 AppWidgetProviderInfo 对象,您将在独立的小组件 XML 文件中对此进行定义。为实现此目的,右键单击您的项目并创建一个名为 xml 的新文件夹。现在,右键单击新创建的文件夹并创建一个新 XML 文件。应将 XML 文件的资源类型设置为 AppWidgetProvider 。在 XML 文件中,定义一些属性,如下所示:

In order to create an application widget, first thing you need is AppWidgetProviderInfo object, which you will define in a separate widget XML file. In order to do that, right click on your project and create a new folder called xml. Now right click on the newly created folder and create a new XML file. The resource type of the XML file should be set to AppWidgetProvider. In the xml file, define some properties which are as follows −

<appwidget-provider
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:minWidth="146dp"
   android:updatePeriodMillis="0"
   android:minHeight="146dp"
   android:initialLayout="@layout/activity_main">
</appwidget-provider>

Widget - Layout file

现在,您必须在默认 XML 文件中定义小组件的布局。您可以拖放组件以生成自动 xml。

Now you have to define the layout of your widget in your default XML file. You can drag components to generate auto xml.

Widget - Java file

在定义布局后,现在创建一个新的 JAVA 文件或使用现有文件,并使用 AppWidgetProvider 类对其进行扩展,并按如下所示覆盖其更新方法。

After defining layout, now create a new JAVA file or use existing one, and extend it with AppWidgetProvider class and override its update method as follows.

在更新方法中,您必须定义两个类的对象,即 PendingIntent 和 RemoteViews。其语法为:

In the update method, you have to define the object of two classes which are PendingIntent and RemoteViews. Its syntax is −

PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);

最后,您必须调用 AppWidgetManager 类中的一个更新方法 updateAppWidget()。其语法为:

In the end you have to call an update method updateAppWidget() of the AppWidgetManager class. Its syntax is −

appWidgetManager.updateAppWidget(currentWidgetId,views);

除了 updateAppWidget 方法,此类中还定义了其他方法以操作小组件。它们如下所示:

A part from the updateAppWidget method, there are other methods defined in this class to manipulate widgets. They are as follows −

Sr.No

Method & Description

1

onDeleted(Context context, int[] appWidgetIds) This is called when an instance of AppWidgetProvider is deleted.

2

onDisabled(Context context) This is called when the last instance of AppWidgetProvider is deleted

3

onEnabled(Context context) This is called when an instance of AppWidgetProvider is created.

4

onReceive(Context context, Intent intent) It is used to dispatch calls to the various methods of the class

Widget - Manifest file

您还必须在清单文件中声明 AppWidgetProvider 类,如下所示:

You also have to declare the AppWidgetProvider class in your manifest file as follows:

<receiver android:name="ExampleAppWidgetProvider" >

   <intent-filter>
      <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
   </intent-filter>

   <meta-data android:name="android.appwidget.provider"
      android:resource="@xml/example_appwidget_info" />
</receiver>

Example

以下是一个示例,演示应用程序小组件的使用。它创建了一个基本的小组件应用程序,其将在浏览器中打开当前网站。

Here is an example demonstrating the use of application Widget. It creates a basic widget applications that will open this current website in the browser.

要使用此示例,您需要在运行因特网的实际设备上运行此示例。

To experiment with this example, you need to run this on an actual device on which internet is running.

Steps

Description

1

You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.

2

Modify src/MainActivity.java file to add widget code.

3

Modify the res/layout/activity_main to add respective XML components

4

Create a new folder and xml file under res/xml/mywidget.xml to add respective XML components

5

Modify the AndroidManifest.xml to add the necessary permissions

6

Run the application and choose a running android device and install the application on it and verify the results.

下面是已修改的 MainActivity.java 的内容。

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MainActivity extends AppWidgetProvider{
   public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
      for(int i=0; i<appWidgetIds.length; i++){
         int currentWidgetId = appWidgetIds[i];
         String url = "https://www.tutorialspoint.com";

         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.setData(Uri.parse(url));

         PendingIntent pending = PendingIntent.getActivity(context, 0,intent, 0);
         RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.activity_main);

         views.setOnClickPendingIntent(R.id.button, pending);
         appWidgetManager.updateAppWidget(currentWidgetId,views);
         Toast.makeText(context, "widget added", Toast.LENGTH_SHORT).show();
      }
   }
}

以下是修改后的 xml res/layout/activity_main.xml 内容。

Following is the modified content of the xml res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textColor="#ff3412ff"
      android:textSize="35dp" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Widget"
      android:id="@+id/button"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="61dp"
      android:layout_below="@+id/textView" />

</RelativeLayout>

以下是 res/xml/mywidget.xml 的内容。

Following is the content of the res/xml/mywidget.xml.

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:minWidth="146dp"
   android:updatePeriodMillis="0"
   android:minHeight="146dp"
   android:initialLayout="@layout/activity_main">
</appwidget-provider>

以下是 res/values/string.xml 的内容。

Following is the content of the res/values/string.xml.

<resources>
   <string name="app_name">My Application</string>
</resources>

下面是 AndroidManifest.xml 文件的内容。

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <receiver android:name=".MainActivity">

      <intent-filter>
         <action android:name="android.appwidget.action.APPWIDGET_UPDATE"></action>
      </intent-filter>

      <meta-data android:name="android.appwidget.provider"
         android:resource="@xml/mywidget"></meta-data>

      </receiver>

   </application>
</manifest>

让我们尝试运行应用程序。我想你已经将你的安卓移动设备连接到你的电脑上了。从安卓工作室运行该应用,打开你的项目活动文件之一,并点击工具栏上的运行图标。在启动应用程序之前,安卓工作室将显示以下窗口来选择运行安卓应用程序的位置。

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the tool bar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.

choose device

选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 −

Select your mobile device as an option and then check your mobile device which will display your default screen −

widget1

转到小组件区域,将你创建的小组件添加到桌面或主屏幕。它将看起来类似于以下内容 –

Go to your widget section and add your created widget to the desktop or home screen. It would look something like this −

widget1

现在只需点击出现的按钮小组件即可启动浏览器。但在这样做之前,请确保你已连接到互联网。按下该按钮后,将出现以下屏幕 –

Now just tap on the widget button that appears, to launch the browser. But before that please make sure that you are connected to the internet. After pressing the button , the following screen would appear −

widget2

注意:只需更改 Java 文件中的 url,你的小组件将在浏览器中打开你想要的网站。

Note. By just changing the url in the java file, your widget will open your desired website in the browser.