微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android – 将AppWidgets添加到活动

我的初始目标是将Google搜索小部件添加到活动的线性布局.我需要包括它就像它出现和工作在Launcher(这就是为什么我需要能够添加的小部件).

我想在我的活动中添加小部件,而不必启动小部件选择器活动.我尝试过了:
直接指定一个整数id(我总是收到充气错误)
2.得到这样的id:

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

(数组一直为空)

这些都没有.

之后,我有这个代码,使用ID(如果我从窗口小部件选择器活动获取ID,它可以工作):

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,newappwidgetproviderInfo);
hostView.setAppWidget(appWidgetId,newappwidgetproviderInfo);

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐