10

Я прочитал несколько вопросов об этом в 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); 
     } 
    } 
} 

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

+0

Попробуйте перезагрузить телефон – apk

+0

Как я уже упоминал в оригинальной публикации, я уже пробовал это. – Andrew

+0

Попробуйте использовать полное имя класса для android: name = "GulpWidgetProvider" на получателе xml? – CSmith

ответ

6

Это вопрос о значениях, установленных вами в 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 Стартом и появляется с размером 1x1

правило для расчета размера 70 × n − 30 где n - это количество ячеек, которое вы хотите. Вы можете найти дополнительную информацию о том, как определить размер виджета here.

+0

Отличный ответ. Благодарю. – Andrew

+0

Заслуживает награду ~ –

+0

Клянусь, я наградил щедростью, когда впервые прочитал ее. Стек только что прислал мне электронное письмо, напоминающее мне об этом, так что вот оно! – Andrew

2

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

+1

Это только, если вы создаете конфигурацию Activity. – Andrew

Смежные вопросы