android - 如何处理 NavController 目标更改?
问题描述
我想实现 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
解决方案
您正在使用R.id.action_numberEntryFragment_to_otpFragment
- 即您正在使用的操作的 ID 。但是,OnDestinationChangedListener
接收到您最终实际要去的目的地app:destination
的 ID -即<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;
}
});
推荐阅读
- asp.net-core - 由于错误“错误:传输出现错误”,SignalR HubConnection 未能成功启动。
- node.js - 添加自定义 ckeditor5 在线构建时,npm 构建失败
- python - 在 nlp 中训练数据以使用 LSTM 提取技能,但训练和验证准确性不如预期
- swift - SwiftUI:使用 HDR/EDR 来增加形状亮度?
- javascript - 为什么我通过加法和乘法得到不同的数字?
- laravel-8 - 传递给 App\Models\User::hasAnyRoles() 的参数 1 必须是数组类型,给定字符串
- flutter - 小部件库捕获的异常═在 null 上调用了方法“+”。接收者:null 尝试调用:+(" ")
- apache-spark - Pyspark 中数组元素上的 UDF 还添加了静态元素
- python - 如何将类型的字符串表示形式转换回 Python 中的类型实例?
- ruby-on-rails - 如果函数调用返回某些内容,Ruby/Rails 将返回结果