我想将默认搜索应用小部件添加到我的应用内的视图中。就像主屏幕,但没有任何拖动,我只希望工作区是4x1大。
我该怎么做?我已经查看了启动器的来源,但需要了解和删除,因为我希望它尽可能简单...
我知道我可以像这样获取小部件的组件名称:
private ComponentName getSearchWidgetProvider() {
SearchManager searchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
ComponentName searchComponent = null;
searchManager.getSearchableInfo(searchComponent);
if (searchComponent == null) return null;
return getProviderInPackage(searchComponent.getPackageName());
}
private ComponentName getProviderInPackage(String packageName) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
if (providers == null) return null;
final int providerCount = providers.size();
for (int i = 0; i < providerCount; i++) {
ComponentName provider = providers.get(i).provider;
if (provider != null && provider.getPackageName().equals(packageName)) {
return provider;
}
}
return null;
}
那么如何以最简单的方式将其添加到视图中(简单地说是一个LinearView)...
谢谢!
答案 0 :(得分:0)
使用AppWidgetHost。我实际上需要这个来存储和读取小部件的包名。看,我们都帮忙了。可以实现AppWidgetHost添加到LnearLayout。如果我是你,我会使用RelativeLayout,因为RelativeLayout允许自定义区域,如果你想让它居中,那么你可以。除非你在RelativeLayout中使用LinearLayout。
以下是它的实施方式:
您可以编辑它并将其更改为您喜欢的方式。调用&#34; appWidgetId&#34;,是每个小部件的int。您可以存储它,然后让您的应用程序检查存储的文件是否存在,读取它,将文本转换为字符串,然后将字符串转换为int。
存储信息:
String path="/sdcard/widget.txt";
//You can change the path to whatever you want it to be
File f=new File(path);
try{
FileWriter fw=new FileWriter(f);
fw.write("whatever text");
fw.flush();
fw.close();
}catch(IOException e){
e.printStackTrace();
}
现在要读取文件,必须调用StringBuilder,BufferedReader和String行来获取信息。
File f=new File("/sdcard/widget.txt");
//the path must be where you stored the files
StringBuilder sb=new StringBuilder();
try{
BufferedReader br=new BufferedReader(new FileReader(f));
String line;
while((line=br.readLine())!=null){
sb.append(line);
sb.append('\n');
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
现在您只需要将文本转换为字符串:
String widId=sb.toStrng();
然后将该String转换为int:
int wid=Integer.parseInt(widId);
现在你在这段代码中强制要求ID:
public void createWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(rl.getWidth(), rl.getHeight()/3);
lp.topMargin = numWidgets * (rl.getHeight()/3);
AppWidgetHostView hostView = mAppWidgetHost.createView(getActivity().getApplicationContext(), appWidgetId, appWidgetInfo);
hostView.setAppWidget(widID,appWidgetInfo);
rl.addView(hostView, lp);
hostView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
numWidgets ++;
}
这会将选定的小部件添加到布局中。