The reason you were given for the error is correct. The fragments are static inner classes, they are in a scope
in which an instance of the Activity does not exist. You then have a method which you call which can only be referenced from an instance of the Activity. Since you don't have an instance, you can't make that call. For this situation, there are two basic fixes.
1) Remove the static keyword from the Fragment class definition. This would tie the definition of the class, and the instances of the class, to an instance of the the Activity and you would gain access to the Activity's instance methods.
2) Call getActivity().getApplicationContext() instead. The method getActivity() comes from the Fragment class and gives you access to the methods of the Activity. If you need a specific method that you added to the Activity, then you would need to cast:((MyActivity)getActivity()).myMethod();
1) Remove the static keyword from the Fragment class definition. This would tie the definition of the class, and the instances of the class, to an instance of the the Activity and you would gain access to the Activity's instance methods.
2) Call getActivity().getApplicationContext() instead. The method getActivity() comes from the Fragment class and gives you access to the methods of the Activity. If you need a specific method that you added to the Activity, then you would need to cast:((MyActivity)getActivity()).myMethod();
The second approach is probably the better one. The Fragment lifecycle is independent of the Activity lifecycle, and by making the Fragment an instance-level inner class you would end up tieing the two together. The FragmentManager may end up not liking it, and there could be issues when you do things like rotatge the screen.
https://coderanch.com/t/632507/Android/Mobile/Error-fix-static-reference-static
本文解释了在Android开发中,当尝试从静态Fragment调用Activity实例方法时遇到的问题,并提供了两种解决方案:一是移除Fragment定义中的static关键字,二是使用getActivity()获取Activity上下文。
1739

被折叠的 条评论
为什么被折叠?



