Aller au contenu

Faire fonctionner un GridView/ListView dans un Widget


NicolasCloutier

Recommended Posts

Bonjour,

Je tente depuis quelques jours de faire fonctionner un Widget, en gros, il va chercher du texte dans une base de donnée locale et l'affiche. Puisque les ScrollView ne sont pas autorisés, je suis obligé de prendre un ListView/GridView pour faire l'équivalent. Mais je n'arrive pas du tout à le faire fonctionner. (C'est la première fois que j'utilise ce type de View). J'ai regardé les samples de Google, la doc et plusieurs sites internet, mais je n'arrive à rien. Je vois la GridView, c'est à dire que je vois le BackGround que je met, mais je ne vois pas du tout de texte s'incruster, même pas le texte par défaut.

Je vous laisse voir... (Oui, je me suis basé sur les samples de Google)

P.S. Je cherche aussi à réactualiser ma GridView avec d'autre données lorsque l'utilisateur clique sur un bouton. Quelqu'un peut m'expliquer la démarche?

EcoWidget.java

public class EcoWidget extends AppWidgetProvider {

   public static final String EXTRA_ITEM = "com.Nic007.EcoTrucs.EXTRA_ITEM";
   public static final String REFRESH_ACTION = "com.Nic007.EcoTrucs.REFRESH_ACTION";

   public void onUpdate(Context context, AppWidgetManager appWidgetManager,
    int[] appWidgetIds) {
        // update each of the app widgets with the remote adapter
        for (int i = 0; i < appWidgetIds.length; ++i) {
            // Set up the intent that starts the EcoWidgetService, which will
            // provide the views for this collection.
            Intent intent = new Intent(context, EcoWidgetService.class);
            // Add the app widget ID to the intent extras.
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            // Instantiate the RemoteViews object for the App Widget layout.
            RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget);
            // Set up the RemoteViews object to use a RemoteViews adapter. 
            // This adapter connects
            // to a RemoteViewsService  through the specified intent.
            // This is how you populate the data.
            rv.setRemoteAdapter(appWidgetIds[i], R.id.gridview, intent);

            // The empty view is displayed when the collection has no items. 
            // It should be in the same layout used to instantiate the RemoteViews
            // object above.
            rv.setEmptyView(R.id.gridview, R.id.widget_item);

            appWidgetManager.updateAppWidget(appWidgetIds[i], rv);   
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

}

EcoWidgetService.java

public class EcoWidgetService extends RemoteViewsService {
   @Override
   public RemoteViewsFactory onGetViewFactory(Intent intent) {
       return new ListeViewFactory(this.getApplicationContext(), intent);
   }
}

class ListeViewFactory implements RemoteViewsService.RemoteViewsFactory {
   private static final int mCount = 3;
   private Context mContext;
   private int mAppWidgetId;
   private String[] items = {"ERREUR", "ERREUR", "ERREUR"};
   private DataBaseHelper dbHelper;
   private ArrayList<Integer> dejaVu;
   private Boolean pasEncoreVu, pasTousVu;
   private int taille, pos;

   public ListeViewFactory(Context context, Intent intent) {
       mContext = context;
       mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
               AppWidgetManager.INVALID_APPWIDGET_ID);
   }

   public void onCreate() {
       // In onCreate() you setup any connections / cursors to your data source. Heavy lifting,
       // for example downloading or creating content etc, should be deferred to onDataSetChanged()
       // or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.

    dbHelper = new DataBaseHelper(null);
       dbHelper = new DataBaseHelper(mContext);

       try 
       {
        dbHelper.createDataBase();
       } catch (IOException ioe) 
       {
 throw new Error("Unable to create database");
       }

    try 
       {
        dbHelper.openDataBase();
       }catch(SQLException sqle)
       {
 throw sqle;
       }

    taille = dbHelper.getSize()-1;

    dejaVu = new ArrayList<Integer>();
    for(int i = 0; i <= taille; i++)
    {
    dejaVu.add(0);
    }

       // We sleep for 3 seconds here to show how the empty view appears in the interim.
       // The empty view is set in the StackWidgetProvider and should be a sibling of the
       // collection view.
       try {
           Thread.sleep(3000);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }

       update();
   }

   public void onDestroy() {
       // In onDestroy() you should tear down anything that was setup for your data source,
       // eg. cursors, connections, etc.
       dbHelper.close();
   }

   public int getCount() {
       return mCount;
   }

   public RemoteViews getViewAt(int position) {

    RemoteViews row = new RemoteViews(mContext.getPackageName(),
               R.layout.widget_item);

    row.setTextViewText(R.id.widget_item, items[position]);
    return(row);
   }

   public RemoteViews getLoadingView() {
       // You can create a custom loading view (for instance when getViewAt() is slow.) If you
       // return null here, you will get the default loading view.
       return null;
   }

   public int getViewTypeCount() {
       return 1;
   }

   public long getItemId(int position) {
       return position;
   }

   public boolean hasStableIds() {
       return true;
   }

   public void onDataSetChanged() {
       // This is triggered when you call AppWidgetManager notifyAppWidgetViewDataChanged
       // on the collection view corresponding to this factory. You can do heaving lifting in
       // here, synchronously. For example, if you need to process an image, fetch something
       // from the network, etc., it is ok to do it here, synchronously. The widget will remain
       // in its current state while work is being done here, so you don't need to worry about
       // locking up the widget.
   }

   public void update()
   {
    pasTousVu = false;

       for(int i = 0; i <= taille; i++)
    {
    if(dejaVu.get(i) == 0)
    {
    pasTousVu = true;
    break;
    }
    }

       if(pasTousVu == false)
       {
        for(int i = 0; i <= taille; i++)
        {
        dejaVu.set(i, 0);
        }
       }

       pasEncoreVu = false;

    do
    {
    Random rdm = new Random();
    pos = rdm.nextInt(taille);

    if(dejaVu.get(pos) == 0)
    pasEncoreVu = true;
    else
    pasEncoreVu = false;

    }while(pasEncoreVu == false);

    dejaVu.set(pos, dejaVu.get(pos) + 1);

       Info info = dbHelper.getDonnees(pos);
       items[0] = info.getTitre();
       items[1] = info.getTexte();
       items[2] = info.getSource();
   }
}</code>

widget_item.xml<code type="xml"><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/widget_item"
   android:layout_width="200dp"
   android:layout_height="20dp"
   android:gravity="center"
   android:text="TEST"
   android:textColor="@color/black"
   android:textSize="12dp" />

widget.xml (Layout)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >


   <FrameLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:padding="@dimen/widget_margin">

       <LinearLayout 
           android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
           >

      <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="48dp"
    android:background="@color/noir">

          <ImageView
              android:id="@+id/icone"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginBottom="4dp"
              android:layout_marginLeft="8dp"
              android:layout_marginTop="4dp"
              android:layout_alignParentTop="true"
              android:layout_alignParentLeft="true"
              android:src="@drawable/icon" />


<ImageButton
  android:id="@+id/btnRefresh"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentRight="true"
  android:layout_alignParentTop="true"
  android:layout_marginBottom="4dp"
  android:layout_marginLeft="8dp"
  android:layout_marginRight="8dp"
  android:layout_marginTop="4dp"
  android:src="@drawable/ic_menu_refresh" />


          <TextView
              android:id="@+id/appNameWidget"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentTop="true"
              android:layout_marginBottom="4dp"
              android:layout_marginLeft="8dp"
              android:layout_marginTop="4dp"
              android:layout_toLeftOf="@id/btnRefresh"
              android:layout_toRightOf="@id/icone"
              android:text="@string/app_name"
              android:textSize="16dp" />

  </RelativeLayout>

      <GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:background="@color/gris"
    android:columnWidth="200dp"
    android:numColumns="1"
    android:verticalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

  </LinearLayout>

</FrameLayout>


</LinearLayout>

Je crois que cela ne sert à rien d'en donner plus. J'avoue que plusieurs bouts de codes restent encore obscur. La documentation est pourrie....

Lien vers le commentaire
Partager sur d’autres sites

Archivé

Ce sujet est désormais archivé et ne peut plus recevoir de nouvelles réponses.

×
×
  • Créer...