覆盖/监听实例化对象中的setMethod

时间:2018-12-02 22:33:46

标签: java android fragment

我想听工厂提供给我的对象中的布尔值。它是该对象内部的值随时间而变化。

我的实际用例: 当片段对用户可见时,我想做些什么,但是我想在Application类(某种类的库)中这样做,所以我不想与用户代码进行交互。

示例代码

this.getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(new FragmentManager
.FragmentLifecycleCallbacks() {
   @Override
   public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {

     if(f.getUserVisibleHint()){
        //do something
     }
     /* unfortunately this code will executed once when fragment is created 
        but the value of "getUserVisibleHint" will be changed 
     */
   }
});

因为mUserVisibleHint是私有的 我轻轻地问,有没有一种方法可以覆盖setUserVisibleHint来知道此变量值已更改?

1 个答案:

答案 0 :(得分:0)

您可以简单地将函数指针发送给应用程序的片段,也可以使用观察者模式。
让我们创建一个在片段可见时调用的接口

public interface FragmentVisibilityListener{
     void onVisibilityChanged(boolean visible, Fragment fragment);
}

然后创建一个片段,该片段告诉我可见或隐藏。

public class FragmentVisibilityHandler{ 
   private static FragmentVisibilityHandler instance;
   private FragmentVisibilityListener visibilityListener;
   public static FragmentVisibilityHandler getInstance(){
          if(instance == null)
             instance = new FragmentVisibilityHandler();
          return instance;
   }
   public void setVisibilityListener(FragmentVisibilityListener listener){
       visibilityListener = listener;
   }
   //you should use this methods in your fragments!
   public void stateChanges(boolean action, Fragment fragment){
         if(visibilityListener != null){
             this.visibilityListener(action,fragment);
         }
   }
}

在片段通话中

public class MyFragment extends Fragment{
@Override
public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        FragmentVisibilityHandler.getInstance().stateChanges(hidden, this);
    }
}

每当您要监听片段更改时,您都可以简单地向其注册visibleListener。例如,在您的应用程序类中:

public class MyApplication extends Application implements FragmentVisibilityListener{
     void inSomeMethod(){
        FragmentVisibilityHandler.getInstance().setVisibilityListener(this);
     }
     void onVisibilityChanged(boolean visible, Fragment fragment){
          Log.i("MyApplication",fragment.toString()+" becomes "+ hidden ? "visible" : "invisible" );
     }
}

您可以创建其他模式进行注册,或者,如果您想监听片段的创建,请使用onViewCreated代替onHiddenChanged