使用 Safe Args 以安全类型传递数据
要将 Safe Args 添加到您的项目中,请在顶级 build.gradle 文件中包含以下类路径:
buildscript {
repositories {
google()
}
dependencies {
def nav_version = "2.3.0"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
}
}
要生成适用于 Java 或混合 Java 和 Kotlin 模块的 Java 语言代码,请将此行添加到您的应用或模块的 build.gradle 文件中:
apply plugin: "androidx.navigation.safeargs"
传递参数Kotlin:
override fun onClick(v: View) {
val amountTv: EditText = view!!.findViewById(R.id.editTextAmount)
val amount = amountTv.text.toString().toInt()
val action = SpecifyAmountFragmentDirections.confirmationAction(amount)
v.findNavController().navigate(action)
}
Java:
@Override
public void onClick(View view) {
EditText amountTv = (EditText) getView().findViewById(R.id.editTextAmount);
int amount = Integer.parseInt(amountTv.getText().toString());
ConfirmationAction action =
SpecifyAmountFragmentDirections.confirmationAction()
action.setAmount(amount)
Navigation.findNavController(view).navigate(action);
}
在您接收目的地的代码中,使用getArguments() 方法检索捆绑包并使用其内容
科特林:
val args: ConfirmationFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val tv: TextView = view.findViewById(R.id.textViewAmount)
val amount = args.amount
tv.text = amount.toString()
}
Java:
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
TextView tv = view.findViewById(R.id.textViewAmount);
int amount = ConfirmationFragmentArgs.fromBundle(getArguments()).getAmount();
tv.setText(amount + "")
}
更多详情:Pass data between destinations