Null Context in setUserVisibleHint

2019-06-28 08:54发布

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() opens an alert dialog with a message.

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 .

Checking isVisibleToUser && isAttached() works in theory, but setUserVisibleHint() is not provoked after isAttached() == true.

Is there some way to allow the call to displayMessage() to wait until the Fragment is attached?

2条回答
男人必须洒脱
2楼-- · 2019-06-28 09:26

It's a bit different approach but more effective solution. Add a new OnPageChangeListenr to your ViewPager.

 yourPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {
                // Check if i == your fragment's position and display message        
                MessageUtility.displayMessage(getContext());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
查看更多
叼着烟拽天下
3楼-- · 2019-06-28 09:34

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);

}
查看更多
登录 后发表回答