这可能是我没有看到的非常简单的事情,或者是我无法确定为什么会发生的非常奇怪的事情。
我有一个活动,和3个片段。
main_fragment
(地图片段)left_menu_fragment
(列表片段用作主菜单)right_menu_fragment
(用作上下文菜单的列表片段)
所以,想象一下类似facebook应用、主要内容和左右菜单的东西。
当我在right_menu_fragment
中更改某些内容时,我希望活动能让main_fragment
知道我更改了一些内容,所以我创建了一个接口。
右菜单进行回调,活动接收回调,并调用main_fragment
中的适当函数,到目前为止一切都很好。
问题是,我正在将对象实例从 当我进行回调时,右菜单在活动中调用此方法: 并且CCD_ 9中的方法实现如下: 正如您所看到的,我验证了我正在接收的变量的某些属性,以确定 我添加指纹只是为了在运行时验证发生了什么。。。好吧,那些本该遇到的"其他事情"有时永远不会发生。我曾经遇到过,一旦调用方法,它首先更新变量,然后在方法中执行代码,或者这就是我推导的。 以下是一个示例日志: 什么时候应该是这样的: 我也试着评论"进行更新"一行,然后它被"解决"了,但当然从来没有进行更新。 我还尝试更改变量名称。无处不在。在 所以,长话短说:我的方法就像"执行更新"行是第一行(你可以清楚地看到它不是) 感谢您的帮助。right_menu_fragment
更新为main_fragment
中同类的另一个实例@Override
public void changedJourneyPreferences(JourneyPreferences journeyPreferences) {
if(mapsFragment != null) {
mapsFragment.setJourneyPreferences(journeyPreferences);
}
}
public void setJourneyPreferences(JourneyPreferences journeyPreferences) {
//first log to verify BEFORE THE UPDATE
boolean foo = false;
//Some verifications new prefs vs old prefs
if(some conditions) {
foo = true;
}
//second log to verify I haven't made the update
this.journeyPreferences = journeyPreferences; //Do the update
//third log to verify I changed properly
//If verifications I made previosly are met
if(foo) {
//do some other things
}
}
boolean
是true
还是false
,然后THEN和ONLY THEN对变量进行更新。first log- old:0 new:0
second log- old:0 new:0
third log- old:0 new:0
first log- old:1 new:1
second log- old:1 new:1
third log- old:1 new:1
first log- old:2 new:2
second log- old:2 new:2
third log- old:2 new:2
first log- old:0 new:0
second log- old:0 new:0
third log- old:0 new:0
first log- old:0 new:1
second log- old:0 new:1
third log- old:1 new:1
first log- old:1 new:2
second log- old:1 new:2
third log- old:2 new:2
right_menu_fragment
和main_fragment
中,以及在setJourneyPreferences
函数中,接收不同调用的变量名。没用。
好的,我发现了错误。
当将局部变量更新为我作为参数接收的变量时,我将自己的变量分配给我正在接收的变量(事实证明,它与另一个片段中的变量完全相同)。
所以我不知道这到底是怎么回事,但我的局部变量变成了,就像一个指针,相同的Id,相同的数据,相同的一切两个不同片段中的两个变量指向完全相同的数据当我从活动调用setJourneyPreferences
时,变量已经更新了,这就是我在更新之前无法验证任何内容的原因。
我解决它的方法是,创建一个新的实例,从参数传递值。一个微小的变化,但它带来了绝对的不同:
替换此行:
this.journeyPreferences = journeyPreferences; //Do the update
有了这个:
//Do the update
this.journeyPreferences = new JourneyPreferences(
journeyPreferences.getMyLocationAs(),
journeyPreferences.getTimeOfJourneyOpts(),
journeyPreferences.getTimeOfJourney());
复制数据,不复制其他内容。