1

Возможно глупый очень вопрос )) Нужно сделать чтобы с установкой приложения устанавливался еще и виджет, как вконтакте. Как это возможно сделать ?

1
  • 1
    А в чём проблема? Создайте класс наследуемый от AppWidgetProvider, добавьте в манифест receiver и файл метаданных в res/xml/
    – Ziens
    10 дек 2016 в 9:32

1 ответ 1

3

Создайте XML файл с метаданными виджета в папке res/xml примерно с таким содержимым

<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/widget"
    android:minHeight="110dp"
    android:minWidth="180dp"
    android:updatePeriodMillis="1800000">
</appwidget-provider>

android:initialLayout="@layout/widget" указывает на файл с разметкой виджета, например такой:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/text"/>
</LinearLayout>

Далее необходимо указать наш виджет в манифесте:

<receiver
    android:name="MyWidget"
    android:icon="@drawable/widget_icon"
    android:label="@string/widget_name">
    <intent-filter>
        <action
            android:name="android.appwidget.action.APPWIDGET_UPDATE">
        </action>
    </intent-filter>
    <meta-data
        android:name="android.appwidget.provider"
        android:resource="@xml/widget_metadata">
    </meta-data>
</receiver>

Ну и сам класс:

public class MyWidget extends AppWidgetProvider {

     static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
         RemoteViews root = new RemoteViews(context.getPackageName(), R.layout.widget);
         appWidgetManager.updateAppWidget(appWidgetId, root);           
      }
      @Override
      public void onUpdate(Context context, AppWidgetManager appWidgetManager,
          int[] appWidgetIds) {
            for (int appWidgetId : appWidgetIds) {
                updateAppWidget(context, appWidgetManager, appWidgetId);
            }
      }

      @Override
      public void onEnabled(Context context) {
      }

      @Override
      public void onDisabled(Context context) {
      }

    }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.