问题描述
当ViewPager中的片段变为可见时,需要向用户显示一条消息.当前的呼叫是:
A message needs to be displayed to the user when a fragment in a ViewPager becomes visible. Currently the call is:
// Within a class that extends Fragment
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
MessageUtility.displayMessage(getContext());
}
}
MessageUtility.displayMessage()
打开一个带有消息的警报对话框.
MessageUtility.displayMessage()
opens an alert dialog with a message.
Context
是显示消息所必需的.但是,不能保证在调用setUserVisibleHint()
时就附加该片段.因此,即使isVisiableToUser == true
,Context
也将是null
.
Context
is required to display the message. However, the fragment is not guaranteed to be attached by the time setUserVisibleHint()
is called. Thus, the Context
will be null
, even though isVisiableToUser == true
.
从理论上讲,检查isVisibleToUser && isAttached()
是可行的,但是isAttached() == true
之后不会引发setUserVisibleHint()
.
Checking isVisibleToUser && isAttached()
works in theory, but setUserVisibleHint()
is not provoked after isAttached() == true
.
是否有某种方法可以允许对displayMessage()
的呼叫等待,直到连接Fragment
为止?
Is there some way to allow the call to displayMessage()
to wait until the Fragment
is attached?
推荐答案
迟到总比没有好,我有一点棘手的解决方案,请从onActivityCreated()
方法调用setUserVisibleHint()
.
Better late than never ,I have a little hackish solution ,call setUserVisibleHint()
from onActivityCreated()
method.
private boolean myIsVisibleToUser;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
myIsVisibleToUser=isVisibleToUser;
if (isVisibleToUser && getActivity()!=null) {
MessageUtility.displayMessage(getContext());
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setUserVisibleHint(myIsVisibleToUser);
}
这篇关于setUserVisibleHint中的空上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!