我是 android 开发的新手,在尝试阅读代码示例时,我遇到了一个从自身内部调用的方法,因此从逻辑上讲,它应该创建一个调用自身的无限循环。但事实并非如此。为什么?
在我的 MainActivity.java
public void onWishlistSelected() {
launchUserSpecificFragment(new WishlistFragment(), WishlistFragment.class.getSimpleName(), new LoginDialogInterface() {
@Override
public void successfulLoginOrRegistration(User user) {
// If login was successful launch WishlistFragment.
onWishlistSelected(); // Why doesn't this create infine loop?
}
});
}
并调用它:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_wish_list) {
onWishlistSelected();
return true;
} else if (id == R.id.action_cart) {
onCartSelected();
return true;
}
return super.onOptionsItemSelected(item);
}
编辑
这是launchUserSpecificFragment
中的代码
private void launchUserSpecificFragment(Fragment fragment, String transactionTag, LoginDialogInterface loginListener) {
if (SettingsMy.getActiveUser() != null) {
replaceFragment(fragment, transactionTag);
} else {
DialogFragment loginDialogFragment = LoginDialogFragment.newInstance(loginListener);
loginDialogFragment.show(getSupportFragmentManager(), LoginDialogFragment.class.getSimpleName());
}
}
和replaceFragment
private void replaceFragment(Fragment newFragment, String transactionTag) {
if (newFragment != null) {
FragmentManager frgManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = frgManager.beginTransaction();
fragmentTransaction.setAllowOptimization(false);
fragmentTransaction.addToBackStack(transactionTag);
fragmentTransaction.replace(R.id.main_content_frame, newFragment).commit();
frgManager.executePendingTransactions();
} else {
Timber.e(new RuntimeException(), "Replace fragments with null newFragment parameter.");
}
}
最佳答案
onWishlistSelected
不 调用自身,所以这里没有无限递归。
它正在调用 launchUserSpecificFragment
,它接收一个实现了 LoginDialogInterface
的匿名类的实例作为参数。
匿名类包含调用 onWishlistSelected
的 successfulLoginOrRegistration
方法,但调用 onWishlistSelected
不一定执行该 successfulLoginOrRegistration
方法。何时执行successfulLoginOrRegistration
取决于launchUserSpecificFragment
的逻辑。
关于java - 为什么这个 java 递归方法不创建无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45781368/