【问题标题】:how to save imageview to sharedpreference using kotlin?如何使用 kotlin 将 imageview 保存到 sharedpreference?
【发布时间】:2020-05-16 00:42:27
【问题描述】:

所以我正在尝试将 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)

请提前帮助和感谢

【问题讨论】:

  • 您正在尝试保存图像,因此这意味着图像是从互联网(URL)加载的。如果是这种情况,您应该使用 Glide 或 Picasso,它们是用于下载、加载和处理缓存的 android-third-party-libraries。此外,如果 Remote 中的图像发生变化,它也会处理。
  • 我在可绘制文件@AmitGupta 中有图像
  • 请检查我添加的答案。希望对您有所帮助。

标签: android android-studio kotlin android-drawable


【解决方案1】:

首先,如果您是 Android 开发新手,请查看Picasso 上传图片。 简而言之,它使使用资源 id/url 上传图片变得更容易/更快。

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

1)如果所有可以选择的图像都已经在应用程序中,您可以将SharedPreferences中的图像资源id保存为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 中,并带有用户的图片属性。并使用毕加索来显示图像。

【讨论】:

  • 你能给我一些关于如何保存资源ID的示例或教程吗?
  • 只需将其保存为整数即可。我已经更新了答案
  • 我试过你的例子,但它仍然没有显示我拥有的两张图片中选择的一张。
  • 您应该在问题中包含您的代码。将资源 ID 保存到共享首选项应该可以。您的代码在其他地方包含错误
  • 我应该把资源 ID 放在哪里?
【解决方案2】:

正如您在 comment提到,您在 res/drawable 文件夹中有图像,并且您希望保存选定的由用户创建的图像,并在用户重新打开应用时加载。

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

会是这样的。

        //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))

希望对你有所帮助。

【讨论】:

猜你喜欢
  • 2014-04-03
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多