1

所以我试图将 Imageview 保存到 sharedpreference 中,所以当用户从它自己的应用程序中选择图像时,如果有意义的话,图像将被保存并设置为 imageview id!当用户退出我的应用程序并重新打开它时,图像将与他保存的图像相同吗?

我尝试了这段代码,但它给了我错误,例如for input string " "

我的共享偏好

CompassBtn.setOnClickListener{


        val  prefCompass = getSharedPreferences("Drawable", Context.MODE_PRIVATE)
        val editor = prefCompass.edit()
        editor.putInt("ic_compass", ic_compass.setImageResource(R.drawable.ic_compass1).toString().toInt())
editor.commit()
    }

**这就是我试图检索它的方式**

   val prfCompass = getSharedPreferences("Drawable", Context.MODE_PRIVATE)
    prfCompass.getInt("ic_compass", 0)

请提前帮助和感谢

4

2 回答 2

2

首先,如果您是 Android 开发新手,请查看Picasso上传图片。简而言之,它可以更轻松/更快地使用资源 id/url 上传图片。

您的问题实际上取决于您希望用户将来选择的图像类型。

1)如果所有可以选择的图像都已经在应用程序中,您可以将图像的资源ID保存SharedPreferences为int

val sharedPref: SharedPreferences = context.getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)

     // Resource id is the int under drawables folder ->R.drawable.myImage
     fun save(KEY_NAME: String, value: Int) {
            val editor: SharedPreferences.Editor = sharedPref.edit()

            editor.putInt(KEY_NAME, value)

            editor.apply()
        }
   fun getInt(KEY_NAME: String): Int {

        return sharedPref.getInt(KEY_NAME, 0)
    }

2)如果您让用户从内部的画廊(这是棘手的部分)中进行onActivityResult选择(在用户选择带有参数的图像后调用Intent data,其中包括图像信息)。访问意图数据(data.getData())将为您提供 URI。然后你需要找到图片的路径(图片在用户手机中的存储路径)并保存到SharedPreferences. 我将把获取图像的路径作为对您的挑战。当你想上传图片时,你可以;

  Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                    Drawable drawable = new BitmapDrawable(getResources(), bitmap);
                    myLayoutItem.setBackground(drawable);

3)如果你有一个服务器,你可以在那里上传你的图像,并将 URL 作为字符串存储在 SharedPreferences/associate url 中,并带有用户的图像属性。并使用毕加索来显示图像。

于 2020-05-16T02:14:02.853 回答
1

正如您在评论中提到的那样,您在res/drawable文件夹中有图像,并且您希望保存用户选择的图像并在用户重新打开应用程序时加载相同的图像。

因此,您要做的就是将resourceId保存在首选项中并使用该值。

这将是这样的。

        //Suppose this is your selected drawable, you need to save its resourceId to shared preferences which is INT value
        val resourceId: Int = R.drawable.your_drawable_image 

        //save resouceId to sharedPreference

        //You can do this to set the Image in the ImageView
        your_imageview.setImageDrawable(getDrawable(resourceId))

我希望这对你有任何帮助。

于 2020-05-16T16:14:38.417 回答