繁体   English   中英

如何在Android小部件中添加活动按钮

[英]How to add activity button in Android widget

这是我第一次需要为Android创建家庭小部件。

我需要在widget_layout定义按钮以启动一些活动,因此我创建了一个WidgetProvider类,该类扩展了AppWidgetProvider并在Home中显示该Widget,但是我注意到没有onCreate ,因此我没有理解如何精确将布局xml中的按钮与可以打开所需活动的侦听器链接起来。

市场上有许多具有这种按钮的小部件。

我应该怎么做?

在窗口小部件中,您必须使用RemoteViews而不是View ,并且没有findViewById() ,因此也没有setOnClickListener() 但是,您可以使用remoteViews.setOnClickPendingIntent(id, pendingIntent) 这是使用此方法打开活动的最小方法:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for (int i = 0; i < appWidgetIds.length; i++) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        Intent appIntent = new Intent(context, MyActivity.class);
        appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent appPendingIntent = PendingIntent.getActivity(context, REQUEST_CODE, appIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        views.setOnClickPendingIntent(R.id.widget_button, appPendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds[i], views);
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM