Androidx Preferences库和DataStore都是Android中用于存储应用程序偏好设置的库。虽然它们的目标相同,但它们在实现和使用上有一些区别。下面是一个比较Androidx Preferences库和DataStore偏好的解决方法,包含代码示例:
implementation 'androidx.preference:preference:1.1.1'
public class MyPreferenceFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, new MyPreferenceFragment())
.commit();
}
}
def datastore_version = "1.0.0-alpha06"
implementation "androidx.datastore:datastore-preferences:$datastore_version"
implementation "androidx.datastore:datastore-core:$datastore_version"
data class UserPreferences(val enableNotifications: Boolean)
class UserPreferencesManager(private val context: Context) {
private val dataStore = context.createDataStore(name = "user_preferences")
val userPreferencesFlow: Flow = dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(UserPreferences(enableNotifications = false))
} else {
throw exception
}
}
.map { preferences ->
UserPreferences(preferences[prefKey] ?: false)
}
suspend fun updateUserPreferences(enableNotifications: Boolean) {
dataStore.edit { preferences ->
preferences[prefKey] = enableNotifications
}
}
companion object {
private val prefKey = booleanPreferencesKey("enable_notifications")
}
}
class MainActivity : AppCompatActivity() {
private lateinit var userPreferencesManager: UserPreferencesManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userPreferencesManager = UserPreferencesManager(context = this)
// 读取偏好设置
lifecycleScope.launch {
userPreferencesManager.userPreferencesFlow.collect { userPreferences ->
// 根据偏好设置更新UI
// ...
}
}
// 更新偏好设置
button.setOnClickListener {
lifecycleScope.launch {
userPreferencesManager.updateUserPreferences(enableNotifications = true)
}
}
}
}
以上是Androidx Preferences库和DataStore偏好的比较,包含代码示例,你可以根据自己的需求选择适合的库来管理应用程序的偏好设置。
上一篇:64位系统装不上-电脑换 64 位系统折腾一下午没装上,技术支持不给力,用户吐槽太闹心
下一篇:AndroidX Preferences异常:“您需要在此活动中使用Theme.AppCompat主题(或后代)。”