我需要打开一个意图来查看图像,如下所示:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("@drawable/sample_1.jpg");
intent.setData(uri);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
问题是这Uri uri = Uri.parse("@drawable/sample_1.jpg");
是不正确的.
Axa*_*dax 134
格式为:
"android.resource://[package]/[res id]"
[package]是你的包名
[res id]是资源ID的值,例如R.drawable.sample_1
将它拼接在一起,使用
Uri path = Uri.parse("android.resource://your.package.name/" + R.drawable.sample_1);
Uli*_*Uli 61
这是一个干净的解决方案,它android.net.Uri
通过其Builder
模式充分利用类,避免重复组合和分解URI字符串,而不依赖于硬编码字符串或关于URI语法的临时想法.
Resources resources = context.getResources();
Uri uri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(resources.getResourcePackageName(resourceId))
.appendPath(resources.getResourceTypeName(resourceId))
.appendPath(resources.getResourceEntryName(resourceId))
.build();
Run Code Online (Sandbox Code Playgroud)
xna*_*gyg 54
public static Uri resourceToUri(Context context, int resID) {
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
context.getResources().getResourcePackageName(resID) + '/' +
context.getResources().getResourceTypeName(resID) + '/' +
context.getResources().getResourceEntryName(resID) );
}
Run Code Online (Sandbox Code Playgroud)
对于那些有错误的人,您可能输入了错误的包名.只需使用此方法.
public static Uri resIdToUri(Context context, int resId) {
return Uri.parse(Consts.ANDROID_RESOURCE + context.getPackageName()
+ Consts.FORESLASH + resId);
}
Run Code Online (Sandbox Code Playgroud)
哪里
public static final String ANDROID_RESOURCE = "android.resource://";
public static final String FORESLASH = "/";
Run Code Online (Sandbox Code Playgroud)
基于上面的答案,我想分享一个关于如何为项目中的任何资源获取有效 Uri 的 kotlin 示例。我认为这是最好的解决方案,因为您不必在代码中输入任何字符串,也不必冒输入错误的风险。
val resourceId = R.raw.scannerbeep // r.mipmap.yourmipmap; R.drawable.yourdrawable
val uriBeepSound = Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(resources.getResourcePackageName(resourceId))
.appendPath(resources.getResourceTypeName(resourceId))
.appendPath(resources.getResourceEntryName(resourceId))
.build()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
81767 次 |
最近记录: |