在onclick上执行代码的小部件

时间:2018-04-16 10:09:16

标签: android android-intent widget android-pendingintent

我想在点击小部件的图标时执行代码 小部件确实具有以下布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:layout_margin="8dip" >
    <ImageView
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="4dip"
        android:src="@drawable/ic_widget" />
</LinearLayout>

我需要在单击ImageView时执行代码 这是Widget的代码:

public class MyWidget extends AppWidgetProvider {

    private static final String WIDGET_BUTTON = "MyWidget.WIDGET_BUTTON";

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

        RemoteViews remoteViews =
                new RemoteViews( context.getPackageName(), R.layout.widget );
        remoteViews.setImageViewResource(R.id.update, R.drawable.ic_widget);

        ComponentName myWidget =
                new ComponentName(context, Button.class);

        Intent intent = new Intent(context, SecurityWidget.class);
        intent.setAction(WIDGET_BUTTON);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
        appWidgetManager.updateAppWidget( myWidget, remoteViews);
    }

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

        if (WIDGET_BUTTON.equals(intent.getAction())) {
            //your code here
            Toast.makeText(context, "EXAMPLE, Toast.LENGTH_LONG).show();
        }
    }
}

这是在AndroidManifest中创建小部件的方式:

<receiver
        android:icon="@drawable/ic_widget"
        android:label="My Widget"
        android:name="MyWidget" >
        <intent-filter >
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="MyWidget.WIDGET_BUTTON" />
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_info" />
    </receiver>

它不起作用。只有在我添加或从主屏幕中删除小部件时才会触发“onReceive”代码。

1 个答案:

答案 0 :(得分:4)

这不应该resources/lang/xx/validation.php代替<Style TargetType="{x:Type ScrollViewer}" BasedOn="{StaticResource {x:Type ScrollViewer}}"> <Setter Property="Tag" Value="Silver"/> <Setter Property="HorizontalScrollBarVisibility" Value="Hidden"/> __YOUR_OTHER_KEYS__ </Style> 吗?

MyWidget.class