您也可以使用logcat中的URL轻松完成此操作,该URL会将您重定向到当前片段源代码的源代码。首先,您需要在主机活动中添加OnBackStackChangedListener,例如-
activity.getChildFragmentManager().addOnBackStackChangedListener(backStackListener);
并且OnBackStackChangedListener实现是-
public FragmentManager.OnBackStackChangedListener backStackListener = () -> {
String simpleName = "";
String stackName = getStackTopName().trim();
if (Validator.isValid(stackName) && stackName.length() > 0) {
simpleName = stackName.substring(Objects.requireNonNull(stackName).lastIndexOf('.') + 1).trim();
List<Fragment >
fragmentList = getChildFragmentManager().getFragments();
Fragment myCurrentFragment;
for (int i = 0; i < fragmentList.size(); i++) {
myCurrentFragment= fragmentList.get(i);
if (myCurrentFragment.getClass().getSimpleName().equals(simpleName)) {
//Now you get the current displaying fragment assigned in myCurrentFragment.
break;
}
myFragment = null;
}
}
//The code below is for the source code redirectable logcat which would be optional for you.
StackTraceElement stackTraceElement = new StackTraceElement(simpleName, "", simpleName + ".java", 50);
String fileName = stackTraceElement.getFileName();
if (fileName == null) fileName = "";
final String info = "Current Fragment is:" + "(" + fileName + ":" +
stackTraceElement.getLineNumber() + ")";
Log.d("now", info + "\n\n");
};
而getStackTopName() 方法是-
public String getStackTopName() {
FragmentManager.BackStackEntry backEntry = null;
FragmentManager fragmentManager = getChildFragmentManager();
if (fragmentManager != null) {
if (getChildFragmentManager().getBackStackEntryCount() > 0)
backEntry = getChildFragmentManager().getBackStackEntryAt(
getChildFragmentManager().getBackStackEntryCount() - 1
);
}
return backEntry != null ? backEntry.getName() : null;
}