我的初始目标是将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);