簡體   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