現在のフラグメントソースコードのソースコードにリダイレクトするlogcatの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;
}