基本上,我从另一个片段创建了新的Fragment by Extended,因为我只想重写某些方法,但仍然继续使用很多方法。
原始片段
public class RestaurantListFragment extends BaseFragment {
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, " :Original :onActivityCreated");
}
}
扩展片段。
public class RestaurantByFoodListFragment extends RestaurantListFragment {
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, " :Modify :onActivityCreated");
}
}
所以当我像这样从
PagerAdapter
调用扩展片段时 @Override
public Fragment getItem(int position) {
switch (position) {
case 0:
case 1:
Log.d(TAG, " :getItem");
restaurantByFoodListFragment = new RestaurantByFoodListFragment();
restaurantByFoodListFragment.setFoodId(this.foodId);
return restaurantByFoodListFragment;
default:
return null;
}
}
好像两个片段中的
onActivityCreated
都被调用了(我只希望扩展对象调用)这是我的日志。
Res List Fragment: :Original :onActivityCreated
Res By Food Fragment: :Modify :onActivityCreated
Res List Fragment: :Original :onActivityCreated
Res By Food Fragment: :Modify :onActivityCreated
那么仅在扩展片段(
onActivityCreated
)内触发RestaurantByFoodListFragment
而不触发原始片段(RestaurantListFragment
)可能吗?谢谢!
最佳答案
您可以通过如下更改类来解决此问题:
public class RestaurantListFragment extends BaseFragment {
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
onActivityCreatedInternal();
}
protected void onActivityCreatedInternal() {
Log.d(TAG, " :Original :onActivityCreated");
}
}
public class RestaurantByFoodListFragment extends RestaurantListFragment {
@Override
protected void onActivityCreatedInternal() {
Log.d(TAG, " :Modify :onActivityCreated");
}
}
您在这里所做的是将
onActivityCreated()
委托给新方法onActivityCreatedInternal()
,并且在子类中您没有调用super.onActivityCreatedInternal()
。这将使您既可以(a)满足所有Fragment子类都调用
super.onActivityCreated()
的要求,又可以(b)通过覆盖被求方法的方法来完全覆盖行为“内部” onActivityCreated()
。关于java - 初始化扩展Fragment时如何停止要调用的父Fragment的onActivityCreated?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56025417/