如何在片段中覆盖Activity的方法

时间:2018-04-05 06:51:17

标签: android android-fragments method-overriding

我想通过活动中添加的片段覆盖活动中存在的方法。

我有以下设置:

BaseActivity

public class BaseActivity extends AppCompatActivity {

    // gets triggered whenever I set a toolbar title
    // from an Activity or Fragment
    public boolean shouldLimitToolbarCharacters () {  
        return true;
    }
}

BaseFragmentActivity

public class BaseFragmentActivity extends BaseActivity implements ToolbarBehaviour {

    // override from BaseActivity and from ToolbarBehaviour
    @Override
    public boolean shouldLimitToolbarCharacters () {

        // instead send it to fragment somehow
        return true;
    }
}

ToolbarBehaviour

 // implemented by BaseFragmentActivity above
 interface ToolbarBehaviour {
     boolean shouldLimitToolbarCharacters();
 }

BaseFragment

public class BaseFragment extends Fragment {

    @Override
    public void onAttach (Context context) {

        if (context instanceof ToolbarBehaviour) {

            ToolbarBehaviour toolbarBehaviour = (ToolbarBehaviour) context;

            // ?? now what
        }
    }
}

如何从BaseFragmentActivity或其子片段覆盖shouldLimitToolbarCharacters()的{​​{1}}?

每当我从BaseFragment的子片段触发shouldLimitToolbarCharacters()时,它应该使用子片段为BaseFragment提供的重写方法。

感谢。

2 个答案:

答案 0 :(得分:3)

method内拨打fragment Activity,如

BaseFragmentActivity

public class BaseFragmentActivity extends BaseActivity implements ToolbarBehaviour {

    BaseFragment fragment; // init in oncreate or something;

    // override from BaseActivity and from ToolbarBehaviour
    @Override
    public boolean shouldLimitToolbarCharacters () {
         if(fragment == null)
            return false;
          return fragment.shouldLimitToolbarCharacters(); 
    }
}

BaseFragment

 public class BaseFragment extends Fragment {

          public boolean shouldLimitToolbarCharacters(){
            return true; // do what ever you want to do 
          }     

    }

答案 1 :(得分:-1)

您可以通过((BaseFragmentActivity )getActivity()).shouldLimitToolbarCharacters();

直接访问活动方法

并像这样使用

@Override
    public void onAttach (Context context) {

        if (context instanceof BaseFragmentActivity) {
         ((BaseFragmentActivity)getActivity()).shouldLimitToolbarCharacters();
        }
    }