android - 是否可以获取Launcher的快捷布局,在我们自己的widget中使用?

标签 android android-layout android-widget android-launcher

我注意到无论我们使用哪个启动器,指定文件夹的类似 Dropbox 快捷方式的小部件的外观都与快捷方式布局一致:

enter image description here enter image description here

所以我想制作这样一个行为和外观都像快捷方式并且与用户的启动器一致的小部件。

是否可以获取Launcher的快捷布局,在我们自己的widget中使用?

最佳答案

除了 AppWidgets 之外,Android 还有一个 Launcher Shortcuts 的概念,通常归类在“Widget”标签下。该 Dropbox 文件夹是启动器快捷方式。

快捷方式很简单,所有数据(图标、标签、 Intent )都是静态的,在创建时确定。它们不能动态更新、调整大小或滚动。但它们与启动器样式相匹配(并且可以放置在文件夹或停靠栏中)并且使用的资源少于 AppWidgets。

遗憾的是,它们的文档记录很差。您可以在 ApiDemos/src/com/example/android/apis/app/LauncherShortcuts.java ( https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/app/LauncherShortcuts.java ) 中找到示例,并在 https://developer.android.com/reference/android/content/Intent.html#EXTRA_SHORTCUT_ICON 中找到对它们的引用(所有 EXTRA_SHORTCUT_... 项目)。

您需要一个 ActivityAndroidManifest intent-filter 来处理快捷方式的创建:

AndroidManifest.xml

<activity
    android:name=".LauncherShortcutActivity" >
    <intent-filter>
        <action android:name="android.intent.action.CREATE_SHORTCUT" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

此 Activity 将由启动器使用 startActivityForResult 调用,您可以呈现一个界面(例如让用户选择快捷方式应该指向的文件夹)但最终必须返回图标、标签和启动器的 Intent 。

void setResult(CharSequence title, int iconResourceId, Intent targetIntent) {
    Intent data = new Intent();
    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, iconResourceId));
    data.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
    data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);
    setResult(Activity.RESULT_OK, data);
    finish();
}

在这种情况下,图标被指定为我的应用程序的资源。或者,图标可以是位图(例如联系人照片):

    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);

关于android - 是否可以获取Launcher的快捷布局,在我们自己的widget中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25334555/

相关文章:

android - 如何通过 android 中的数据绑定(bind)将 onTextChanged 监听器添加到包含布局 xml

android - LinearLayout 中的启动画面图像背景不适合

android - Activity 中的滑动效应

java - 渲染期间引发异常 : ScrollView can host only one direct child

android - 错误 :Failed to find: com. google.guava :guava:18. 0.+

android - 如何在android中自定义ListView的高度?

android - 在android小部件中从数据库获取数据

android - Android中如何减少图片的内存使用

android - Listview 在 Android 上禁用内部滚动

android - 具有自定义 View 的小部件宿主应用程序 - 在应用程序小部件中不会触发 onClick