返回片段UI时如何刷新 [英] How to refresh fragment UI when come back to it
问题描述
我是Android的新手,正在学习带片段的东西,并为此做了一个演示,因为我有一个片段,可以从该片段转到另一个活动,在那里进行一些计算,然后返回到碎片当时我想将该计算值分配到片段的textview中,那么我应该使用哪种生命周期方法呢?我已经使用过onresume了,但是这是行不通的...
I am new to android and learning things with fragments and have made a demo for it,in that i am having a fragment from which we can go to another activity at there some calculation is performing and after that we come back to frgament at that time i want to dislay that calculation value to my fragment's textview,So which life cycle method should i use to do so?i already used onresume which is not working...
public void onResume () {
super.onResume();
//tvFollowings.setText((sharedConnect.getCurrentUser().userFollowingCount)
// + " Following");
System.out.print("------user count is-------" + String.valueOf(sharedConnect.getCurrentUser().userFollowingCount));
Toast.makeText(getActivity(), "------user count is-------" + String.valueOf(sharedConnect.getCurrentUser().userFollowingCount), Toast.LENGTH_SHORT).show();
}
推荐答案
最好的方法是在onPause和onResume之间切换.甚至不必打扰家长活动
The best approach which works, toggle between onPause and onResume. No need to even bother the parent activity
private boolean allowRefresh = false;
@Override
public void onResume() {
super.onResume();
//Initialize();
if(allowRefresh){
allowRefresh=false;
//call your initialization code here
}
}
@Override
public void onPause() {
super.onPause();
if (!allowRefresh)
allowRefresh = true;
}
onResume总是在您的片段加载时被调用,因此allowRefresh的初始状态应该为false,这样片段不会被加载两次
onResume will always be called when your fragment gets loaded, so initial state of allowRefresh should be false so the fragment does not get loaded twice
在片段处于活动状态时打开新活动后,将调用onPause,仅在allowRefresh为false的情况下,将allowRefresh设置为true.
Once you open new activity whilst the fragment is active, onPause is called, here set allowRefresh to true only if allowRefresh is false.
当片段重新获得焦点时,请检查allowRefresh是否为true并重做初始化.良好的代码习惯是将所有初始化代码放在一个函数中.
When the fragment regains focus, check if allowRefresh is true and redo your initialization. A good code practice is put all your initialization code in one function.
这篇关于返回片段UI时如何刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!