Android - 将 AppWidgets 添加到 Activity

Android - adding AppWidgets to an Activity(Android - 将 AppWidgets 添加到 Activity)

本文介绍了Android - 将 AppWidgets 添加到 Activity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初的目标是将 Google 搜索小部件添加到活动的线性布局中.我需要包含它,就像它在启动器中显示和工作一样(这就是我需要能够添加小部件的原因).

我想在我的活动中添加小部件,而不必启动小部件选择器活动.我尝试过了:

1.直接指定一个整数 id(我总是得到 inflate 错误)

I would like to add widgets to my activity whithout having to launch the widget picker activity. I tried to:

1. directly specify an integer id (I always get inflate errors)

2.像这样获取 id:

2. get the id like this:

  ComponentName cn = new ComponentName(getBaseContext(), "com.android.quicksearchbox.SearchWidgetProvider");
  int[] ids = AppWidgetManager.getInstance(getApplicationContext()).getAppWidgetIds (cn);

(数组始终为空)

这些都不起作用.

在此之后,我有了这段代码,以使用 ID(如果我从小部件选择器活动中获取 ID,它就可以工作):

After this I have this code, to use the ID (it works if I get the ID from the widget picker activity):

    AppWidgetProviderInfo withWidgetInfo = AppWidgetManager.getInstance(getApplicationContext()).getAppWidgetInfo(appWidgetId);
    AppWidgetHostView hostView = myWidgetHost.createView(getBaseContext(), appWidgetId, withWidgetInfo);
    hostView.setAppWidget(appWidgetId, withWidgetInfo);
    LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
    ll.addView(hostView);

我该怎么做?谢谢!

推荐答案

试试这个:

// APPWIDGET_HOST_ID is any number you like
appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
AppWidgetProviderInfo newAppWidgetProviderInfo = new AppWidgetProviderInfo();

// Get an id
int appWidgetId = appWidgetHost.allocateAppWidgetId();

// Get the list of installed widgets
List<AppWidgetProviderInfo> appWidgetInfos = new ArrayList<AppWidgetProviderInfo>();
appWidgetInfos = appWidgetManager.getInstalledProviders();

for(int j = 0; j < appWidgetInfos.size(); j++)
{
    if (appWidgetInfos.get(j).provider.getPackageName().equals("com.android.quicksearchbox") && appWidgetInfos.get(j).provider.getClassName().equals("com.android.quicksearchbox.SearchWidgetProvider"))
    {
        // Get the full info of the required widget
        newAppWidgetProviderInfo = appWidgetInfos.get(j);
        break;
    }
 }

// Create Widget
AppWidgetHostView hostView = appWidgetHost.createView(this, appWidgetId, newAppWidgetProviderInfo);
hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

// Add it to your layout
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ll.addView(hostView);

编辑:

要绑定小部件 ID,即让小部件更新并响应用户交互,请参阅此处的解决方案:小部件在重新时不响应- 通过代码添加

To bind widget IDs, i.e. make widgets update and respond to user interaction, refer the solution here: Widgets don't respond when re-added through code

这篇关于Android - 将 AppWidgets 添加到 Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Android - 将 AppWidgets 添加到 Activity

基础教程推荐