【问题标题】:Update app widget on click in android在android中点击更新应用小部件
【发布时间】:2011-12-26 11:56:59
【问题描述】:

我正在开发 Android 小部件,我的小部件如下图所示, [prev] 事件名称 [next]

上一个,下一个是小部件上的按钮。所以我想在单击下一个和上一个按钮时更新事件名称。在服务启动时,我加载数据并将其存储在数组列表中。现在我想通过单击小部件上的下一个和上一个按钮来遍历数组列表。

那么我该如何实现这一点。请帮助我找到正确的解决方案。 这是我的 xml 布局

<LinearLayout
    android:id="@+id/lytWidget2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dip"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/btnPreviousView"
        android:layout_width="43dp"
        android:layout_height="fill_parent"
        android:layout_gravity="left|center"
        android:background="@drawable/ic_leftarrow"
        android:padding="5dip" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="52dp"
        android:layout_weight="0.97"
        android:text="Event Name" />

    <Button
        android:id="@+id/btnNextView"
        android:layout_width="43dp"
        android:layout_height="fill_parent"
        android:layout_gravity="right|center_vertical"
        android:background="@drawable/ic_rightarrow"
        android:padding="5dip" />
</LinearLayout>

【问题讨论】:

  • 你能发布你的 xml 布局和小部件的代码吗?
  • 我用 xml 布局更新了问题,请帮帮我。

标签: android android-widget android-appwidget


【解决方案1】:

因此,只需像这样处理 AppWidgetProvider 类中按钮的单击事件。 请参阅这个关于如何创建简单小部件的好教程。还添加了点击处理程序。

示例代码

 @Override 
 public void onReceive(Context context, Intent intent) 
 { 
      super.onReceive(context, intent); 

      RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
      // find your TextView here by id here and update it.

      Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show(); 
 } 

【讨论】:

  • 感谢您的回答。但是如何通过单击按钮来更新小部件的文本视图(在上一个和下一个按钮之间)。
  • 是的,你可以。阅读教程,它有很好的例子如何实现这一点。有一个示例小部件项目可以极大地帮助您。
  • 但示例直接打开活动。但我想更新小部件的当前视图而不打开任何东西。查看 Facebook 小部件,您可以通过单击下一个和上一个按钮查看用户的帖子。
  • 这应该真的能得到答案。
  • 只有在拖动小部件时才会触发。如何在点击时触发它
【解决方案2】:

首先,在您的 WidgetProviderClass 中,您应该定义您的操作,以便区分它们。在这种情况下:

private static final String ACTION_UPDATE_CLICK_NEXT = "action.UPDATE_CLICK_NEXT";
private static final String ACTION_UPDATE_CLICK_PREVIOUS = "action.UPDATE_CLICK_PREVIOUS";

接下来,您应该在覆盖的 onUpdate() 函数中输入:

@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

            RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.your_widget_layout);

            views.setOnClickPendingIntent(R.id.nextButtonWidget, getPendingSelfIntent(context, ACTION_UPDATE_CLICK_NEXT));
            views.setOnClickPendingIntent(R.id.previousButtonWidget, getPendingSelfIntent(context, ACTION_UPDATE_CLICK_PREVIOUS));

}

用于创建指向当前类(自身)的意图的函数:

private PendingIntent getPendingSelfIntent(Context context, String action) {

        Intent intent = new Intent(context, getClass()); // An intent directed at the current class (the "self").
        intent.setAction(action);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    }

当事件发生时onReceive()函数会被调用:

    @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);


            if (ACTION_UPDATE_CLICK_NEXT.equals(intent.getAction())) {
                 // if the user clicked next
                }


            else if (ACTION_UPDATE_CLICK_PREVIOUS.equals(intent.getAction())) {
                // if the user clicked previous
        }

}

奖励: 如果你想调用onUpdate() 函数,这里有一个函数可以为你做这件事。 它只需要上下文参数!

/**
 * A general technique for calling the onUpdate method,
 * requiring only the context parameter.
 *
 * @author John Bentley, based on Android-er code.
 * @see <a href="http://android-er.blogspot.com
 * .au/2010/10/update-widget-in-onreceive-method.html">
 * Android-er > 2010-10-19 > Update Widget in onReceive() method</a>
 */

private void onUpdate(Context context) {

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    ComponentName thisAppWidgetComponentName = new ComponentName(context.getPackageName(), getClass().getName());
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName);
    onUpdate(context, appWidgetManager, appWidgetIds);
}

【讨论】:

    【解决方案3】:

    NewAppWidget.java

    package com.example.android.appwidgetsample;
    
    import android.app.PendingIntent;
    import android.appwidget.AppWidgetManager;
    import android.appwidget.AppWidgetProvider;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.widget.RemoteViews;
    
    import java.text.DateFormat;
    import java.util.Date;
    
    /**
     * App widget provider class, to handle update broadcast intents and updates
     * for the app widget.
     */
    public class NewAppWidget extends AppWidgetProvider {
    
        // Name of shared preferences file & key
        private static final String SHARED_PREF_FILE =
                "com.example.android.appwidgetsample";
        private static final String COUNT_KEY = "count";
    
        /**
         * Update a single app widget.  This is a helper method for the standard
         * onUpdate() callback that handles one widget update at a time.
         *
         * @param context          The application context.
         * @param appWidgetManager The app widget manager.
         * @param appWidgetId      The current app widget id.
         */
        private void updateAppWidget(Context context,
                                    AppWidgetManager appWidgetManager,
                                    int appWidgetId) {
    
            // Get the count from prefs.
            SharedPreferences prefs =
                    context.getSharedPreferences(SHARED_PREF_FILE, 0);
            int count = prefs.getInt(COUNT_KEY + appWidgetId, 0);
            count++;
    
            // Get the current time.
            String dateString =
                    DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
    
            // Construct the RemoteViews object.
            RemoteViews views = new RemoteViews(context.getPackageName(),
                    R.layout.new_app_widget);
            views.setTextViewText(R.id.appwidget_id,
                    String.valueOf(appWidgetId));
            views.setTextViewText(R.id.appwidget_update,
                    context.getResources().getString(
                        R.string.date_count_format, count, dateString));
    
            // Save count back to prefs.
            SharedPreferences.Editor prefEditor = prefs.edit();
            prefEditor.putInt(COUNT_KEY + appWidgetId, count);
            prefEditor.apply();
    
            // Setup update button to send an update request as a pending intent.
            Intent intentUpdate = new Intent(context, NewAppWidget.class);
    
            // The intent action must be an app widget update.
            intentUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    
            // Include the widget ID to be updated as an intent extra.
            int[] idArray = new int[]{appWidgetId};
            intentUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, idArray);
    
            // Wrap it all in a pending intent to send a broadcast.
            // Use the app widget ID as the request code (third argument) so that
            // each intent is unique.
            PendingIntent pendingUpdate = PendingIntent.getBroadcast(context,
                    appWidgetId, intentUpdate, PendingIntent.FLAG_UPDATE_CURRENT);
    
            // Assign the pending intent to the button onClick handler
            views.setOnClickPendingIntent(R.id.button_update, pendingUpdate);
    
            // Instruct the widget manager to update the widget.
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    
        /**
         * Override for onUpdate() method, to handle all widget update requests.
         *
         * @param context          The application context.
         * @param appWidgetManager The app widget manager.
         * @param appWidgetIds     An array of the app widget IDs.
         */
        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                             int[] appWidgetIds) {
            // There may be multiple widgets active, so update all of them.
            for (int appWidgetId : appWidgetIds) {
                updateAppWidget(context, appWidgetManager, appWidgetId);
            }
        }
    }
    

    NewAppWidget.xml

    <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:background="#09C"
                    android:padding="@dimen/widget_margin" >
    
        <!-- Panel for Widget ID -->
        <LinearLayout
            android:id="@+id/section_id"
            style="@style/AppWidgetSection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:orientation="horizontal">
    
            <TextView
                android:id="@+id/appwidget_id_label"
                style="@style/AppWidgetLabel"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="@string/widget_id_label"/>
    
            <TextView
                android:id="@+id/appwidget_id"
                style="@style/AppWidgetText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="end"
                android:text="XX"/>
        </LinearLayout>
    
        <!-- Panel for widget update date and number of updates -->
        <LinearLayout
            android:id="@+id/section_update"
            style="@style/AppWidgetSection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/section_id"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/appwidget_update_label"
                style="@style/AppWidgetLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="2dp"
                android:text="@string/widget_update_label"/>
    
            <TextView
                android:id="@+id/appwidget_update"
                style="@style/AppWidgetText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/date_count_format"/>
        </LinearLayout>
    
        <!-- Update widget button -->
        <Button
            android:id="@+id/button_update"
            style="@style/AppWidgetButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/section_update"
            android:layout_centerHorizontal="true"
            android:text="@string/widget_button_update" />
    </RelativeLayout>
    

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多