【问题标题】:How to define multiple sharedPreferences?如何定义多个 sharedPreferences?
【发布时间】:2019-06-05 16:55:49
【问题描述】:

我已经设法获得 sharedPreferences 保存值。但我不知道如何让它引用我点击的文本。在// Close Alert Window 部分,当我单击确定更改文本时。确定关闭警报对话框,然后假设将新价格添加到sharedPreferences 中列出。

putString() 中,如果我使用putString("Price$it", input.text.toString()).apply,它似乎什么也没做。但是,如果我使用"Price1",我更改的任何文本都会保存,并且在重新打开应用程序时Price1会更改为新价格。所以我知道这个方法是有效的。我只是不知道如何保存我正在编辑的特定文本。我希望这是有道理的。感谢您的宝贵时间。

// Created Private Price List
    val sharedPreferences = getSharedPreferences("priceList", Context.MODE_PRIVATE)

//Price
    (1..912).forEach {
        val id = resources.getIdentifier("Price$it", "id", packageName)
        val tv = findViewById<TextView>(id)
        tv.text = sharedPreferences.getString("Price$it","0.00")

    }

(1..912).forEach {
        val id = resources.getIdentifier("Price$it", "id", packageName)
        val tv = findViewById<TextView>(id)
        tv.setOnLongClickListener {

            //Alert Window
            val alertDialog = AlertDialog.Builder(this@MainActivity).create()
            alertDialog.setTitle("NEW PRICE")
            val input = EditText(this@MainActivity)
            //Alert Submit on Enter
            input.setOnKeyListener { v, keyCode, event ->
                if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    // Input changes text
                    tv.text = input.text
                    when {
                        tv.text.startsWith("-") -> tv.setTextColor(Color.RED)
                        tv.text.startsWith("+") -> tv.setTextColor(Color.GREEN)
                    else -> {
                        tv.text = "_"
                        tv.setTextColor(Color.DKGRAY)
                    }
                    }
                    // Close Alert Window
                    alertDialog.dismiss()
                    // TODO Save Price Table  //THIS PART vvv
                    sharedPreferences.edit().putString("Price1", input.text.toString()).apply()
                }
                false
            }


            val lp = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            input.layoutParams = lp
            alertDialog.setView(input)
            alertDialog.show()
            return@setOnLongClickListener true

        }
    }

【问题讨论】:

    标签: string foreach kotlin android-edittext sharedpreferences


    【解决方案1】:

    您正在跟踪it。在您的范围内,您引用​​了tv.setOnLongClickListener 的参数。指定参数名称,使其不受内部 lambda 的影响。

    (1..912).forEach { index ->
        ...
        sharedPreferences.edit().putString("Price$index", input.text.toString()).apply()
    }    
    

    【讨论】:

    • 谢谢,我不可能知道这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2021-09-29
    • 2013-07-30
    • 2014-08-09
    • 2016-04-13
    相关资源
    最近更新 更多