如果我有以下代码,如何在android中保存设置?

时间:2019-06-09 15:01:01

标签: android kotlin android-alertdialog

我是android的新手,发现很难理解一些概念。

我有一个设置活动,该活动具有可单击的线性布局。 每个可单击的线性布局均包含一个项目和一个子项目。 我希望该子项目可以修改,尽管在修改之前已将其设置为一些默认值。

<ScrollView
    <LinearLayout
        android:orientation="vertical" >
        <LinearLayout"
            android:orientation="horizontal"
            android:clickable="true" >
            <TextView
               <!-- this is Item --> 
               android:text="@string/settings_enabled_days"/>
               <!-- android:text="Enabled Days" -->
            <TextView
               <!-- this is sub Item --> 
               android:text="@string/settings_enabled_days_value" />
               <!-- android:text="Mon, Tue, Wed, Fri, Sat" -->
        </LinearLayout>

现在我有以下设置活动代码,我在评论中提出了疑问:

class SettingsActivity : AppCompatActivity() {

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

        val enabledDays = findViewById<LinearLayout>(R.id.settings_enabled_days)
        enabledDays.setOnClickListener { showEnabledDaysDialog() }

    }

    private fun showEnabledDaysDialog() {
        // I have declared arrayChecked to make the app working
        // But I want it to be stored somewhere so that I can modify its default values later
        val arrayChecked = booleanArrayOf(false, true, true, true, true, true, false)
        val selectedDays = ArrayList<Int>()

        val enabledDaysBuilder = AlertDialog.Builder(this)
        enabledDaysBuilder.setTitle(R.string.settings_enabled_days)
        enabledDaysBuilder.setMultiChoiceItems(R.array.days_long, arrayChecked) { _, which, isChecked ->
            if (isChecked)
                selectedDays.add(which)
            else if (selectedDays.contains(which))
                selectedDays.remove(Integer.valueOf(which))
        }
        enabledDaysBuilder.setPositiveButton(R.string.dialog_ok) { dialog, which -> 
            // I don't know what to do here
            // I want selectedDays to modify the default values
            // I also don't know where to store those default values 
        }
        enabledDaysBuilder.setNegativeButton(R.string.dialog_cancel) { _, _ ->
            // do not modify anything
        }

        val enabledDaysDialog = enabledDaysBuilder.create()
        enabledDaysDialog.show()
    }
}

这是 array.xml 文件中的 days_long 数组

<string-array name="days_long">
    <item>Sunday</item>
    <item>Monday</item>
    <item>Tuesday</item>
    <item>Wednesday</item>
    <item>Thursday</item>
    <item>Friday</item>
    <item>Saturday</item>
</string-array>

1 个答案:

答案 0 :(得分:0)

您应该查看SharedPreferences。您可以保存布尔状态,这些状态在应用程序关闭并重新打开时仍然存在。然后,您可以阅读SharedPreferences以恢复“设置”。

https://developer.android.com/training/data-storage/shared-preferences