实施Android Jetpack首选项
设置页面让用户能够定制他们在应用程序中的互动。它是一种改善整体用户体验的绝佳方法。
例如,像YouTube这样的应用程序允许用户在黑暗和光明模式之间进行选择,挑选视频质量,调节通知以及其他特征,只需一次点击即可。
设置屏幕通过允许用户声明他们的偏好来增强用户的体验。
因此,我们需要找到最直接、最有效的方法,在我们的应用程序中加入偏好设置。
在这篇文章中,我们将使用JetPack首选项库创建一个简单的设置屏幕。
前提条件
要继续学习本教程,你需要具备以下条件。
- 具有Android开发的基本知识。
- 对Kotlin编程语言有一定了解。
- 有关[Android偏好]的基本知识
- 安装了[Android Studio]。
第1步 - 创建一个新项目
打开Android Studio,选择新项目->空活动作为你的项目模板,然后点击next 。
给应用程序起任何名字。在我的例子中,我将把这个项目命名为Android Preferences。
我们将使用Kotlin 作为这个项目的编程语言。把其他一切都保留为默认,然后点击Finish 。然后等待几秒钟,让Android Studio建立起这个项目。
第2步 - 在MainActivity中添加一个菜单
菜单使用户能够添加一个(几个)菜单项,以帮助导航到SettingActivity 。
我们将通过为每个项目(s)添加一个click listener 来实现这一功能。按照下面的步骤,添加一个menu 资源文件。
在project 目录中,右键单击res 文件夹,添加一个new resource file -> new -> Android resource file 。
接下来,导航到Android资源文件,输入文件名和资源类型为menu ,然后点击OK ,完成。
在menu 包内,选择new -> menu resource 文件,然后将其命名为setting_menu ,点击finish 。
在settings_menu 文件中添加以下几行代码。
<item
android:id="@+id/setting"
android:icon="@drawable/ic_settings"
android:visible="true"
android:contentDescription="@string/my_setting"
app:showAsAction="ifRoom"
android:title="@string/settings"/>
为了确保菜单栏是可见的,在MainActivity.kt 文件中添加以下代码。
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.settings_menu, menu)
return true
}
第3步 - 添加第二个活动
在这一步,我们将在项目中添加 "设置 "活动。导航到主文件夹并添加一个新的活动。记住要在确认对话框中选择一个Settings activity 。-
几个文件将与 "设置 "活动一起被生成。它们包括。
-
layout文件夹中的一个默认的settings.xml文件。当你打开资源文件时,有一个叫做root preferences的布局,所有的设置都将在这里得到体现。几个preference categories,将容纳一个特定的设置组。 -
一个新的价值资源文件称为
arrays。它包含了将对用户可见的条目和值。
我们需要在数组中包含新的值,用于我们的设置偏好。因此,我们应该删除default 数组并添加新的数组值,如下所示。
<resources>
<string-array name="theme_entries">
<item>Light</item>
<item>Dark</item>
<item>Use system theme</item>
</string-array>
<string-array name="theme_values">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
<string-array name="download_entries">
<item>Default (100MB)</item>
<item>1.0 MB</item>
<item>4.7 MB</item>
<item>10.6 MB</item>
<item>32 MB</item>
<item>50 MB</item>
<item>Disable</item>
</string-array>
<string-array name="download_values">
<item>default(100_mb)</item>
<item>1.0_mb</item>
<item>4.7_mb</item>
<item>10.6_mb</item>
<item>32_mb</item>
<item>50_mb</item>
<item>disable</item>
</string-array>
</resources>
我们将在一般偏好类别中为我们的列表偏好有theme 值和条目。
用户在设置应用程序时将选择他们喜欢的主题和下载尺寸。
注意,使用drawables是可选的。然而,你可以从矢量资产中添加你的drawables。
在根偏好布局中添加下面的代码。它将包含我们将在应用程序中使用的所有偏好。
<PreferenceCategory app:title="Personal details"
app:icon="@drawable/ic_person_pin">// It is the holder of a particular group of settings
<EditTextPreference
app:key="myEditText"
app:title="Enter your name"
app:useSimpleSummaryProvider="true" />
<CheckBoxPreference
app:title="Mood check"
app:summary="Check the text box if you like our design layout"
app:key="pref"
app:defaultValue="true"
/>
<SeekBarPreference
app:title="Rate this app"
app:showSeekBarValue="true"
app:icon="@drawable/ic_baseline_star"
app:summary="Rate this app in a scale of 0 -> 5"
app:key="rating_bar"
android:max="5"
app:min="0"
app:defaultValue="3"
app:dependency="pref"
/>
</PreferenceCategory>
<PreferenceCategory app:title="General"
app:icon="@drawable/ic_baseline_color_lens">
<ListPreference
app:dialogTitle="Theme"
app:defaultValue="1"
app:entryValues="@array/theme_values"
app:entries="@array/theme_entries"
app:key="theme"
app:useSimpleSummaryProvider="true"
app:title="Choose your Theme"/>
</PreferenceCategory>
<PreferenceCategory app:title="Chat features"
app:icon="@drawable/ic_baseline_app_settings">
<SwitchPreferenceCompat
app:key="chat_features"
app:summary="Use Wi-Fi or data for messaging when available"
app:title="Enable chat features"/>
<SwitchPreferenceCompat
app:dependency="chat_features"
app:key="attachment"
app:summaryOff="Let others know you have read their message "
app:summaryOn="Other people will see you have read their text automatically"
app:title="Send read receipts" />
<SwitchPreferenceCompat
app:dependency="chat_features"
app:key="attachment"
app:title="Show type indicators"
app:summaryOff="Let others know your are typing"
app:summaryOn="Other people will see whenever you are typing"
/>
<ListPreference
app:defaultValue="default(100_mb)"
app:entries="@array/download_entries"
app:entryValues="@array/download_values"
app:key="default(100_mb)"
app:title="Auto-download files you receive over mobile data"
app:useSimpleSummaryProvider="true"
app:dependency="chat_features"/>
</PreferenceCategory>
<PreferenceCategory app:title="Others"
app:icon="@drawable/ic_read_more">
<Preference
app:title="Android Preferences"
android:summary="That was all we had for today. Feel free to add more Android preferences in your application before we meet next time.
Thank you."
/>
</PreferenceCategory>
下面是根首选项中的关键属性。它们对于理解它们在应用程序中的每个偏好中的用法至关重要。
-
app: key- 它允许开发者对首选项进行额外的调整。 -
app: summary- 一个描述特定首选项的字符串。 -
app: title和 - 它们显示一个特定的偏好或类别偏好的标题。而 ,则是与屏幕上弹出的特定对话框相联系。dialog: titledialog title -
default: value- 这种设置偏好有更多的选择,而且必须作为默认值包括在内。它表示开发者在用户改变应用程序之前进行初始设置。 -
summary: on- 多用于开关中。它强调了开关时将被设置的字符串。 -
summary: off- 当开关被设置为关闭时,一个字符串被设置。 -
app: dependency- 它表示一个特定的设置偏好取决于另一个偏好的功能。依赖性必须被设置为真,其他功能才能工作。
第4步 - 在MainActivity.kt上工作
我们需要实现在两个活动之间导航的能力。因此,我们应该在MainActivity 中添加一个意图。
为了实现这个功能,在MainActivity.kt 文件中添加以下代码。
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.setting -> {
Toast.makeText(this,"You are getting ready for android preferences",Toast.LENGTH_LONG).show()
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
}
}
return super.onOptionsItemSelected(item)
}
上面的代码使用其id ,调用了菜单item 。然后,我们在点击后显示一条敬酒信息。接下来,我们传递我们需要导航到的活动的意图。
为了使用setting activity 工具栏中的返回按钮导航回MainActivity ,在manifest.xml 文件中的设置活动中添加以下代码。
android:parentActivityName=".MainActivity"
上面的代码通知当前的activity(child) ,一旦点击了后退按钮,它就应该转到MainActivity 。
第5步 - 在SettingActivity.kt上工作
我们需要使我们的设置发挥作用。
用户将能够从浅色、深色或系统默认主题中进行选择。要添加这一功能,请在SettingsActivity中包含以下代码。
class SettingsActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener{
//Other codes.
}
为了注册我们的共享偏好,在support action bar?.set 行下面添加以下代码。
supportActionBar?.setDisplayHomeAsUpEnabled(true)
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this)
我们需要确保应用程序采用一个新的主题。我们在SettingActivity 类中重写onSharedPreferenceChanged, 。
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == "theme"){
val pref = sharedPreferences?.getString(key,"1")
when(pref?.toInt()){
1 ->{
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_NO)
}
2 ->{
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES)
}
3 ->{
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
}
}
}
在上面的代码中,if 语句检查我们是否在正确的偏好上,使用其键。
在这种情况下,我们检查我们是否在一般偏好类别的列表偏好中。
如果键是正确的,我们使用when 控制流程,在点击时将每个值设置为正确的主题。
我们还需要销毁我们注册的共享偏好,因为我们已经完成了使用它们。这样可以节省内存空间。要取消对共享偏好的注册,请使用下面的代码。
override fun onDestroy() {
super.onDestroy()
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this)
}
第6步 - 运行应用程序
你可以在虚拟设备(仿真器)或物理设备上运行该应用程序。
总结
在这篇文章中,我们讨论了如何在应用程序中使用Android首选项。