如何使用Kotlin将图像视图保存为共享首选项?

问题描述 投票:0回答:2

因此,我试图将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)

请事先提供帮助和感谢,谢谢

android android-studio kotlin android-drawable
2个回答
1
投票

首先,如果您不熟悉Android开发,请检查Picasso上传图像。简而言之,使用资源ID / URL可以更轻松/更快地上传图像。

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

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

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作为字符串存储在具有image属性为user的SharedPreferences / associate url中。并使用毕加索显示图像。


0
投票

您在comment

© www.soinside.com 2019 - 2024. All rights reserved.