【发布时间】:2020-05-06 17:32:52
【问题描述】:
我正在尝试保存主题。我在 drwable 文件夹中有主题(图像)。我正在显示图像列表,单击相同的图像我想将选定的可绘制资源保存在 sharedpreferences 中并从 sharedpreferences 中获取相同的资源。
为此,我想将可绘制资源转换为 uri 并将 uri 转换为字符串。
我尝试将 drawable 转换为 uri,如下所示:
public static String getURLForResource (int resourceId,Context context) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
/* return Uri
.parse("android.resource://"+ BuildConfig.APPLICATION_ID +
"/" +resourceId).toString();*/
Resources resources = context.getResources();
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
+ resources.getResourcePackageName(resourceId) + '/'
+ resources.getResourceTypeName(resourceId) + '/'
+ resources.getResourceEntryName(resourceId)).toString();
}
并从 sharedprefences 中检索此 uri 字符串并尝试将其转换为位图:
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap =
BitmapFactory.decodeFile(sharedPreferencesData.getStr(
"ThemeName"),
options);*/
/* Uri myUri = Uri.parse(sharedPreferencesData.getStr(
"ThemeName"));
*/
/* Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));
ContentResolver res = getContentResolver();
InputStream in = null;
try {
in = res.openInputStream(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap artwork = BitmapFactory.decodeStream(in);*/
try {
Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));
Bitmap bitmap =
MediaStore.Images.Media
.getBitmap(this.getContentResolver(), uri);
/*
InputStream stream =
getAssets().open(sharedPreferencesData.getStr(
"ThemeName"));
Drawable d = Drawable.createFromStream(stream, null);
URL url_value = new URL(sharedPreferencesData.getStr(
"ThemeName").trim());
Bitmap mIcon1 =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
*/
我尝试了多种方法,但都没有奏效。位图为空,或者我收到 File not found 异常和 malformedException。
请帮忙。
编辑:
我从 getURLForResource 得到以下字符串:
D/ImageUri: android.resource://com.dailyfaithapp.dailyfaith/drawable/theme0
我创建了一个带有主题名、字体等的类...并且我将值设置为相同的值:
public void setThemes(){
Themes themes = new Themes();
themes.setId(1);
themes.setImage(Utils.getURLForResource(R.drawable.theme1,this));
themes.setFont("AlexBrush-Regular.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(2);
themes.setImage(Utils.getURLForResource(R.drawable.theme2,this));
themes.setFont("SkinnyJeans.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(3);
themes.setImage(Utils.getURLForResource(R.drawable.theme3,this));
themes.setFont("Roboto-Thin.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(4);
themes.setImage(Utils.getURLForResource(R.drawable.theme4,this));
themes.setFont("Raleway-Light.ttf");
themesArrayList.add(themes);
}
【问题讨论】:
-
如果您想检查图像的颜色,那么为什么要这么麻烦?
-
它不仅仅是颜色。我想将图像保存为主题并将其应用于主屏幕@blackapps
-
你仍然没有明确你想要什么或者你的代码应该做什么。
-
请检查编辑@blackapps
-
您没有告诉 getURLForResource() 返回哪个值。
标签: android uri android-drawable android-bitmap filenotfoundexception