是否可以使用Jetpack Navigation为导航操作设置默认参数值?
我有一个fragment
,需要参数。我希望使用"1"
时该参数的值为navController.navigate(R.id.action1)
,使用"2"
时该参数的值为navController.navigate(R.id.action2)
。
<fragment
android:id="@+id/myFragment"
android:name="MyFragment">
<argument android:name="action_number" />
</fragment>
<!-- action_number should be set to 1 -->
<action
android:id="@+id/action1"
app:destination="@id/myFragment" />
<!-- action_number should be set to 2 -->
<action
android:id="@+id/action2"
app:destination="@id/myFragment" />
答案 0 :(得分:0)
使用Safe Args传递安全类型的数据
要将安全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"
传递古怪品科特琳:
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