【问题标题】:Dependency in rootpreferences Android Studiorootpreferences Android Studio 中的依赖关系
【发布时间】:2021-09-26 15:49:11
【问题描述】:

我在 android studio 中的 root_preferences.xml 中存在依赖问题。我想为我的应用添加简单的设置,但其中一些设置仅适用于女性或男性。

所以我在这里有简单的 CheckBoxPreference

<CheckBoxPreference
            app:key="pregnant"
            app:title="Pregnant"
            app:defaultValue="false"/>

只有在您提交性别时选中第一个活动上的单选按钮时才应启用它

 <RadioButton
        android:id="@+id/Female"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:text="Female"
        android:buttonTint="@color/black"/>

那么我怎样才能为男性禁用此 CheckBoxPreference 并为女性启用它?

【问题讨论】:

  • 禁用RadioButton 非常简单,但您的问题缺少大量信息。 第一个活动是什么?是登录页面吗?信息保存在哪里?性别是否存储在root_preferences.xml 中?
  • 如果用户是男性,我想禁用复选框首选项,我尝试在 sharedpreferences 中保存布尔值,但我不知道如何从代码中禁用复选框首选项,而不是从 xml 中

标签: java android dependencies radio-button android-preferences


【解决方案1】:

您可以尝试使用 Radio Group 选择一个单选按钮..根据此您可以检查选择了哪个单选按钮男性或女性您可以显示或隐藏您想要的

【讨论】:

  • RadioButtonCheckBoxPreference 不在同一个屏幕中。我想你误解了这个问题。
  • 这管理起来并不复杂。我刚刚分享了方式,所以请通过intent.putextra("gender",selectedgender)方法将男性或女性状态从活动第一到第二传递如果单选按钮和复选框首选项不在同一个屏幕中。只需要在第二个屏幕中更新您的复选框首选项。
【解决方案2】:

试试这样的。

首先,你要保存用户是男是女。

    // Create class/object to store your Keys
    object KeyConstants {
        const val KEY_IS_FEMALE = "isFemale"
    }

    // Somewhere in your First Activity
    val isFemale = femaleRadioButton.isChecked
    PreferenceManager.getDefaultSharedPreferences(context)
            sharedPrefs.edit()
                .putBoolean(KeyConstants.KEY_IS_FEMALE, isFemale)
                .apply()

然后在你的PreferenceFragmentCompat阅读它:

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)

            val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
            val isFemale = sharedPrefs.getBoolean(KeyConstants.KEY_IS_FEMALE, false)

            // This will make it enabled when female and disabled when male
            preferenceScreen.findPreference<CheckBoxPreference>("pregnant")?.isEnabled = isFemale
        }

【讨论】:

    猜你喜欢
    • 2016-03-06
    • 2018-04-22
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多