【问题标题】:how to save and retrieve application info to shared preference in kotlin?如何在 kotlin 中保存和检索应用程序信息以共享首选项?
【发布时间】:2020-11-29 13:44:34
【问题描述】:

我想从网格视图中隐藏应用程序图标并保存它。 我可以将应用程序信息作为可变设置字符串保存到共享首选项并获取它,但无法将字符串转换为应用程序信息并显示在我的网格视图中

我的应用活动

private var applist: List<ApplicationInfo>? = null
private var listadaptor: ApplicationAdapter? = null
private var grid: GridView? = null

private var mSelected: ArrayList<Any> = ArrayList()
var context: Activity = this

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_apps)

   val packageManager = getPackageManager()
   LoadApplications().execute()
   grid = findViewById<View>(R.id.grid) as GridView
   grid!!.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE)
   grid!!.adapter = listadaptor
   grid!!.onItemClickListener = AdapterView.OnItemClickListener { parent: AdapterView<*>?, view: View?, position: Int, id: Long ->
       val app = applist!![position]
       try {
           val intent = packageManager.getLaunchIntentForPackage(app.packageName)
           intent?.let { startActivity(it) }
       } catch (e: Exception) {
           Toast.makeText(this@appsActivity, e.message, Toast.LENGTH_LONG).show()
       }
   }
   grid!!.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->

       val position1: String = (position).toString()
       if (mSelected.contains(position1)) {
           mSelected.remove(position1)
           view.setBackgroundColor(Color.TRANSPARENT) // remove item from list
           // update view (v) state here
           // eg: remove highlight
       } else {
           mSelected.add(position1)
           view.setBackgroundColor(Color.LTGRAY) // add item to list
           // update view (v) state here
           // eg: add highlight
       }
       button3.setOnClickListener(
               object : View.OnClickListener {
                   override fun onClick(view: View?) {
                       val builder1: AlertDialog.Builder = AlertDialog.Builder(this@appsActivity)
                       builder1.setMessage("Are you sure you want to delete it ?")
                       builder1.setCancelable(true)
                       builder1.setPositiveButton(
                               "Yes",
                               DialogInterface.OnClickListener { dialog, id ->

                                   deleteSelectedItems()
                                   mSelected.remove(position)
                                   listadaptor!!.notifyDataSetChanged()

                                   val app = applist!![position]
                                   listadaptor!!.remove(app)
                               })
                       builder1.setNegativeButton(
                               "No",
                               DialogInterface.OnClickListener { dialog, id -> dialog.cancel() })
                       val alert11: AlertDialog = builder1.create()
                       alert11.show()
                   }
               })
       true
   }
}
private fun deleteSelectedItems() {
    val checked: SparseBooleanArray = grid!!.getCheckedItemPositions()
    if (checked != null) {
        val list: List<Any> = mSelected
        for (i in 0 until checked.size()) {
            if (checked.valueAt(i)) {
                mSelected.remove(checked.keyAt(i))
            }
        }
    }
}
private fun checkForLaunchIntent(list: List<ApplicationInfo>): List<ApplicationInfo> {
    val applist = ArrayList<ApplicationInfo>()
    for (info in list) {
        try {
            if (null != packageManager!!.getLaunchIntentForPackage(info.packageName)) {
                applist.add(info)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    Collections.sort(applist, ApplicationInfo.DisplayNameComparator(packageManager))
    return applist
}
@SuppressLint("StaticFieldLeak")
private inner class LoadApplications : AsyncTask<Void?, Void?, Void?>() {
    override fun doInBackground(vararg params: Void?): Void? {

        applist = checkForLaunchIntent(packageManager!!.getInstalledApplications(
                PackageManager.GET_META_DATA))
        listadaptor = ApplicationAdapter(this@appsActivity,
                R.layout.grid_item, applist!!)
        return null
    }
    override fun onPostExecute(result: Void?) {
        grid!!.adapter = listadaptor
        super.onPostExecute(result)
    }
}

项目被删除,但重新运行应用程序后,所有已安装的应用程序都会在gridview中恢复

【问题讨论】:

    标签: kotlin gridview sharedpreferences show-hide android-applicationinfo


    【解决方案1】:

    您可以查看我的开源项目LibTron,它有一个module 库,用于用 Kotlin 编写的 SharedPref。 要使用该库,请按照项目自述文件中的说明进行操作 使用该库的示例:

    val applicationInfo: ApplicationInfo = sharedprefrence.Object(name = "sharedprefKey", defaultValue = null)
    

    或者如果您想在没有帮助的情况下使用它,您可以使用 GSON、Moshi、Jackson 类型库在保存或读取 Sharedprefrence 时将字符串转换为/从字符串转换为 ApplicationInfo 类

    【讨论】:

    • 对不起,我是初学者。我不明白。请提供完整的来源
    • 你能提供你想要实现的源代码吗?
    猜你喜欢
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多