我正在使用一个PreferenceActivity并实现onPreferenceChange方法。我正在检查更改了什么首选项,这样我就可以执行它了,但是,.equals()方法始终返回false。我已经调试了这个应用程序,它显示了两个字段都返回字符串student_id。我是不是遗漏了什么?此时,更改来自student_id_key首选项更改。
来自strings.xml
<string name="student_id_key" translatable="false">student_id</string>onPreferenceChange中的代码
if(preference.getKey().equals(preference.getContext().getString(R.string.student_id_key))){
//do something here, but its returning false
}下面是调试器的快照,将x和y显示为两个字符串

我试过使用==,但结果是一样的

这是我的prefs.xml中元素的摘录
<EditTextPreference
android:capitalize="words"
android:defaultValue="@string/student_id_default"
android:inputType="textCapWords"
android:hint="@string/student_id_hint"
android:key="@string/student_id_key"
android:maxLines="1"
android:maxLength="9"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="@string/pref_title_display_name" />发布于 2016-06-30 23:38:01
对于字符串比较,请始终使用.equals,因为==不会(嗯,除非您将相同的变量与其自身进行比较)不会对字符串有效,因为它们是不可变的。
编辑:所以,我认为这是因为在这个块中没有代码(或者任何重要的代码)。在该块中添加一个print语句,并查看它是否打印。编译器对死代码进行优化,因此它可能会让您认为在没有死代码的情况下发生了一些奇怪的事情。
https://stackoverflow.com/questions/38134694
复制相似问题