Виджет не отображается в списке виджетов

Я прочитал несколько вопросов об этом в stackoverflow, и ни один из ответов не решает мою проблему.

Я пытаюсь добавить виджет главного экрана в свое приложение, но мой виджет не отображается в списке виджетов Android.

Я пытался перезагрузить устройство, переустановить приложение, изменить параметры в файле конфигурации, убедиться, что приложение не установлено на SD-карту. Ничего не работает.

Вот код, который у меня сейчас есть:

Внутри тега приложения AndroidManifest.xml:

<receiver
    android:name=".GulpWidgetProvider"
    android:icon="@mipmap/ic_launcher"
    android:label="Gulp">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data
        android:name="android.appwidget.provider"
        android:resource="@xml/gulp_widget_info" />
</receiver>

Внутри /res/xml/gulp_widget_info.xml:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/layout_widget"
    android:minHeight="150dip"
    android:minWidth="400dip"
    android:updatePeriodMillis="86400000"
    android:widgetCategory="home_screen"
    android:resizeMode="none"
    android:minResizeHeight="150dip"/>

Внутри /res/layout/layout_widget.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="150dip"
    android:background="@drawable/gradient"
    android:gravity="center_horizontal|top">

    <RelativeLayout
        android:layout_width="170dip"
        android:layout_height="150dip"
        android:gravity="center">


        <ProgressBar
            android:id="@+id/widget_consumption_progress_bar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="150dip"
            android:layout_height="150dip"
            android:layout_centerInParent="true"
            android:indeterminate="false"
            android:max="100"
            android:progress="0"
            android:progressDrawable="@drawable/progressbar"
            android:secondaryProgress="100" />

        <ProgressBar
            android:id="@+id/widget_time_progress_bar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="150dip"
            android:layout_height="150dip"
            android:layout_centerInParent="true"
            android:indeterminate="false"
            android:max="100"
            android:progress="0"
            android:progressDrawable="@drawable/progressbar2"
            android:secondaryProgress="100" />

        <TextView
            android:id="@+id/widget_water_consumed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:fontFamily="sans-serif-light"
            android:gravity="center"
            android:maxLines="1"
            android:textColor="@color/white"
            android:textSize="30sp" />

        <TextView
            android:id="@+id/widget_unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/water_consumed"
            android:layout_centerInParent="true"
            android:fontFamily="sans-serif-light"
            android:gravity="center"
            android:maxLines="1"
            android:text="@string/milliliters_abbrev"
            android:textColor="@color/white"
            android:textSize="12sp" />

    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingLeft="10dip"
        android:paddingRight="10dip">


        <TextView
            android:id="@+id/widget_add"
            style="@style/GulpButton"
            android:layout_width="60dip"
            android:layout_height="60dip"
            android:background="@drawable/whitecirclebutton"
            android:gravity="center"
            android:text="@string/add_abbrev" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/widget_goal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:textColor="@color/white"
                android:textSize="22sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:text="@string/target"
                android:textColor="@color/white_semi_translucent"
                android:textSize="14sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/widget_remaining"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:textColor="@color/white"
                android:textSize="22sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:text="@string/remaining"
                android:textColor="@color/white_semi_translucent"
                android:textSize="14sp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

Внутри /java/info/andrewdahm/gulp/GulpWidgetProvider.java:

public class GulpWidgetProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            // Create an Intent to launch ExampleActivity
            Intent intent = new Intent(context, Main.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.layout_widget);
            views.setOnClickPendingIntent(R.id.widget_add, pendingIntent);

            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}

Есть идеи, почему мой виджет не отображается в списке виджетов?


person Andrew    schedule 06.05.2015    source источник
comment
Попробуйте перезагрузить телефон   -  person amodkanthe    schedule 06.05.2015
comment
Как я уже упоминал в исходном посте, я уже пробовал это.   -  person Andrew    schedule 06.05.2015
comment
Попробуйте использовать полное имя класса для android:name=GulpWidgetProvider в XML-получателе?   -  person CSmith    schedule 06.05.2015
comment
@CSmith Вы предлагаете ставить точку перед GulpWidgetProvider? Пример: android:name=".GulpWidgetProvider". Я только что сделал это, и виджет все еще не отображается в списке.   -  person Andrew    schedule 06.05.2015
comment
укажите полный путь к классу, например. com.yourcompany.yourapp.gulp.GulpWidgetProvider. Это всего лишь предположение, как я это сделал.   -  person CSmith    schedule 06.05.2015
comment
@CSmith Все еще не повезло.   -  person Andrew    schedule 07.05.2015


Ответы (2)


Это проблема со значениями, которые вы установили в gulp_widget_info.xml для android:minHeight и android:minWidth.

Попробуйте установить меньшие значения, и виджет должен появиться в списке виджетов лаунчера:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/layout_widget"
    android:minHeight="40dip"
    android:minWidth="40dip"
    android:updatePeriodMillis="86400000"
    android:widgetCategory="home_screen"
    android:resizeMode="none" />

Я проверил эти настройки на своем телефоне с помощью Google Now Launcher, и они отображаются с размером 1x1.

Правило расчета размера – 70 × n − 30, где n – необходимое количество ячеек. Дополнительную информацию о том, как определить размер виджета, можно найти здесь.

person Mattia Maestrini    schedule 10.05.2015
comment
Отличный ответ. Спасибо. - person Andrew; 11.05.2015
comment
Клянусь, я присудил награду, когда впервые прочитал это. Стек только что прислал мне электронное письмо с напоминанием об этом, так что вот оно! - person Andrew; 18.05.2015

В соответствии с этой ссылкой действие должно быть объявлено в XML-файле AppWidgetProviderInfo, с атрибутом android:configure, и вам этого не хватает.

person bilal    schedule 17.05.2015
comment
Это только в том случае, если вы создаете действие конфигурации. - person Andrew; 18.05.2015