我想通过活动中添加的片段覆盖活动中存在的方法。
我有以下设置:
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
提供的重写方法。
感谢。
答案 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();
}
}