如何处理NavController目标页面的变化?

3
我想使用addOnDestinationChangedListener,但是一直没有成功。我已经试着自己实现了,但是ID不匹配。
NavController mController = Navigation.findNavController(this, R.id.nav_auth_fragment);
mController.addOnDestinationChangedListener((controller, destination, arguments) -> {
    switch (destination.getId()){
        case R.id.action_loginFragment_to_numberEntryFragment:
            Toast.makeText(this, "Welcome to number Entry", Toast.LENGTH_SHORT).show();
            break;
        case R.id.action_numberEntryFragment_to_otpFragment:
            Toast.makeText(this, "Enter your OTP", Toast.LENGTH_SHORT).show();
            break;
        case R.id.action_otpFragment_to_userRegistrationFragment:
            Toast.makeText(this, "Your number is verified!", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
    }
});

我尝试记录下来并且这里是结果:

2019-11-04 11:39:17.179 26830-26830/com.example.myapp D/AuthActivity: 2131230930 == 2131230775 = false
2019-11-04 11:39:17.179 26830-26830/com.example.myapp D/AuthActivity: 2131230930 == 2131230781 = false
2019-11-04 11:39:17.180 26830-26830/com.example.myapp D/AuthActivity: 2131230930 == 2131230782 = false
where 2131230930 is the destination.getId() and (2131230775, 2131230781, 2131230782) is the resource ids
even when I'm at the destination, the id still doesn't match with the resource id

这段代码是在Activity还是Fragment中? - coroutineDispatcher
请参考此链接:https://dev59.com/AFcP5IYBdhLWcg3w_vAU - Archu Mohan
@coroutineDispatcher 代码在活动中。 - eightmoons
@ArchuMohan 谢谢你,但是我没有安装支持存储库的问题。 - eightmoons
1个回答

5

您正在使用R.id.action_numberEntryFragment_to_otpFragment,即您正在使用的操作的ID。然而,OnDestinationChangedListener 接收实际到达的目标的 ID,即<action> 上的 app:destination 字段。

因此,您应该使用目标 ID(只是猜测您的目标 ID 是什么):

mController.addOnDestinationChangedListener((controller, destination, arguments) -> {
    switch (destination.getId()){
        case R.id.numberEntryFragment:
            Toast.makeText(this, "Welcome to number Entry", Toast.LENGTH_SHORT).show();
            break;
        case R.id.otpFragment:
            Toast.makeText(this, "Enter your OTP", Toast.LENGTH_SHORT).show();
            break;
        case R.id.userRegistrationFragment:
            Toast.makeText(this, "Your number is verified!", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接