如何处理 NavController 目的地更改?

eig*_*ons 3 android android-jetpack android-jetpack-navigation

我想实现 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;
    }
});
Run Code Online (Sandbox Code Playgroud)

我尝试记录它,这是结果

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
Run Code Online (Sandbox Code Playgroud)

ian*_*ake 5

您正在使用- 即您正在使用的操作R.id.action_numberEntryFragment_to_otpFragment的 ID 。但是,会收到您最终实际要去的目的地的 ID ,即上的字段。OnDestinationChangedListenerapp:destination<action>

因此,您应该使用目标 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;
    }
});
Run Code Online (Sandbox Code Playgroud)