繁体   English   中英

Jetpack Navigation 中操作的默认参数值

[英]Default argument value for action in Jetpack Navigation

是否可以使用 Jetpack Navigation 为导航操作设置默认参数值?

我有一个需要论证的fragment 我希望在使用 navController.navigate(R.id.action1) 时此参数的值为"1" ,在使用navController.navigate(R.id.action1) navController.navigate(R.id.action2) "2"

<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" />

使用 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"
    }
}

To generate Java language code suitable for Java or mixed Java and Kotlin modules, add this line to your app or module's build.gradle file:

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()方法检索包并使用其内容

Kotlin:

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 + "")
}

有关更多详细信息: 在目的地之间传递数据

您可以使用<argument>标记在<action>标记内提供默认值。

例如,您的第一个操作将变为:

    <action
        android:id="@+id/action1"
        app:destination="@id/myFragment">
        <argument
            android:name="action_number"
            android:defaultValue="1"/>
    </action>

在参数中使用默认值,

例如:-

<action
    android:id="@+id/action1"
    app:destination="@id/myFragment">
    <argument
        android:name="value"
        android:defaultValue="1"/>
</action>ode here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM