Skip to content

Commit

Permalink
feat:navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
qianran committed May 4, 2020
1 parent a452bd1 commit 9d179b9
Show file tree
Hide file tree
Showing 3 changed files with 209 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package com.holiday.jetpackstudy.navigation;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavDestination;
import androidx.navigation.NavOptions;
import androidx.navigation.Navigator;
import androidx.navigation.fragment.FragmentNavigator;

import java.lang.reflect.Field;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;

/**
* 支持fragment复用的导航器,搜"//fix"可快速定位到修复点
*/
@Navigator.Name("fixFragment") //fix 5: 需要指定1个名字,源码里自带的名字有navigation、activity、fragment、dialog
public class FixFragmentNavigator extends FragmentNavigator {
private static final String TAG = "FixFragmentNavigator";
private Context mContext;
private FragmentManager mFragmentManager;
private int mContainerId;

public FixFragmentNavigator(@NonNull Context context, @NonNull FragmentManager manager, int containerId) {
super(context, manager, containerId);
mContext = context;
mFragmentManager = manager;
mContainerId = containerId;
}

@Nullable
@Override
public NavDestination navigate(@NonNull Destination destination, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) {
if (mFragmentManager.isStateSaved()) {
Log.i(TAG, "Ignoring navigate() call: FragmentManager has already"
+ " saved its state");
return null;
}
String className = destination.getClassName();
if (className.charAt(0) == '.') {
className = mContext.getPackageName() + className;
}
//fix 1: 把类名作为tag,寻找已存在的Fragment
//(如果想只针对个别fragment进行保活复用,可以在tag上做些标记比如加个前缀)
Fragment frag = mFragmentManager.findFragmentByTag(className);
if (null == frag) {
//不存在,则创建
frag = instantiateFragment(mContext, mFragmentManager, className, args);
}

frag.setArguments(args);
final FragmentTransaction ft = mFragmentManager.beginTransaction();

int enterAnim = navOptions != null ? navOptions.getEnterAnim() : -1;
int exitAnim = navOptions != null ? navOptions.getExitAnim() : -1;
int popEnterAnim = navOptions != null ? navOptions.getPopEnterAnim() : -1;
int popExitAnim = navOptions != null ? navOptions.getPopExitAnim() : -1;
if (enterAnim != -1 || exitAnim != -1 || popEnterAnim != -1 || popExitAnim != -1) {
enterAnim = enterAnim != -1 ? enterAnim : 0;
exitAnim = exitAnim != -1 ? exitAnim : 0;
popEnterAnim = popEnterAnim != -1 ? popEnterAnim : 0;
popExitAnim = popExitAnim != -1 ? popExitAnim : 0;
ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim);
}

// ft.replace(mContainerId, frag);
//fix 2: replace换成show和hide
List<Fragment> fragments = mFragmentManager.getFragments();
for (Fragment fragment : fragments) {
ft.hide(fragment);
}
if (!frag.isAdded()) {
ft.add(mContainerId, frag, className);
}
ft.show(frag);
ft.setPrimaryNavigationFragment(frag);

final @IdRes int destId = destination.getId();

//fix 3: mBackStack是私有的,而且没有暴露出来,只能反射获取
ArrayDeque<Integer> mBackStack;
try {
Field field = FragmentNavigator.class.getDeclaredField("mBackStack");
field.setAccessible(true);
mBackStack = (ArrayDeque<Integer>) field.get(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}

final boolean initialNavigation = mBackStack.isEmpty();
final boolean isSingleTopReplacement = navOptions != null && !initialNavigation
&& navOptions.shouldLaunchSingleTop()
&& mBackStack.peekLast() == destId;

boolean isAdded;
if (initialNavigation) {
isAdded = true;
} else if (isSingleTopReplacement) {
if (mBackStack.size() > 1) {
mFragmentManager.popBackStack(
generateBackStackName(mBackStack.size(), mBackStack.peekLast()),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.addToBackStack(generateBackStackName(mBackStack.size(), destId));
}
isAdded = false;
} else {
ft.addToBackStack(generateBackStackName(mBackStack.size() + 1, destId));
isAdded = true;
}
if (navigatorExtras instanceof Extras) {
Extras extras = (Extras) navigatorExtras;
for (Map.Entry<View, String> sharedElement : extras.getSharedElements().entrySet()) {
ft.addSharedElement(sharedElement.getKey(), sharedElement.getValue());
}
}
ft.setReorderingAllowed(true);
ft.commit();
if (isAdded) {
mBackStack.add(destId);
return destination;
} else {
return null;
}
}

//fix 4: 从父类那边copy过来即可
@NonNull
private String generateBackStackName(int backStackIndex, int destId) {
return backStackIndex + "-" + destId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.FragmentNavigator;
import androidx.navigation.fragment.NavHostFragment;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.holiday.jetpackstudy.R;
import com.holiday.jetpackstudy.navigation.ui.dashboard.DashboardFragment;
import com.holiday.jetpackstudy.navigation.ui.home.HomeFragment;
import com.holiday.jetpackstudy.navigation.ui.notifications.NotificationsFragment;

/**
* https://juejin.im/post/5c53be3951882562d27416c6
Expand All @@ -27,12 +33,62 @@ protected void onCreate(Bundle savedInstanceState) {
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
// AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
// R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
// .build();
// NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
// NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
// NavigationUI.setupWithNavController(navView, navController);

//fragment复用
//获取页面容器NavHostFragment
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
//获取导航控制器
NavController navController = NavHostFragment.findNavController(fragment);
//创建自定义的Fragment导航器
FixFragmentNavigator fragmentNavigator =
new FixFragmentNavigator(this, fragment.getChildFragmentManager(), fragment.getId());
//获取导航器提供者
NavigatorProvider provider = navController.getNavigatorProvider();
//把自定义的Fragment导航器添加进去
provider.addNavigator(fragmentNavigator);
//手动创建导航图
NavGraph navGraph = initNavGraph(provider, fragmentNavigator);
//设置导航图
navController.setGraph(navGraph);
//底部导航设置点击事件
navView.setOnNavigationItemSelectedListener(item -> {
navController.navigate(item.getItemId());
return true;
});
// NavigationUI.setupWithNavController(navView, navController);//这种方式有问题,有待研究
}

//手动创建导航图,把3个目的地添加进来
private NavGraph initNavGraph(NavigatorProvider provider, FixFragmentNavigator fragmentNavigator) {
NavGraph navGraph = new NavGraph(new NavGraphNavigator(provider));

//用自定义的导航器来创建目的地
FragmentNavigator.Destination destination1 = fragmentNavigator.createDestination();
destination1.setId(R.id.navigation_home);
destination1.setClassName(HomeFragment.class.getCanonicalName());
destination1.setLabel(getResources().getString(R.string.title_home));
navGraph.addDestination(destination1);

FragmentNavigator.Destination destination2 = fragmentNavigator.createDestination();
destination2.setId(R.id.navigation_dashboard);
destination2.setClassName(DashboardFragment.class.getCanonicalName());
destination2.setLabel(getResources().getString(R.string.title_dashboard));
navGraph.addDestination(destination2);

FragmentNavigator.Destination destination3 = fragmentNavigator.createDestination();
destination3.setId(R.id.navigation_notifications);
destination3.setClassName(NotificationsFragment.class.getCanonicalName());
destination3.setLabel(getResources().getString(R.string.title_notifications));
navGraph.addDestination(destination3);

navGraph.setStartDestination(R.id.navigation_home);

return navGraph;
}
}
4 changes: 2 additions & 2 deletions app/src/main/res/layout/activity_navigation.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
app:layout_constraintBottom_toTopOf="@id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
app:layout_constraintTop_toTopOf="parent" />
<!-- app:navGraph="@navigation/mobile_navigation"-->

</androidx.constraintlayout.widget.ConstraintLayout>

0 comments on commit 9d179b9

Please sign in to comment.