Navigation Compopent的使用之fragment之间使用Safe Args安全地传递数据

1、在project的build.gradle的dependencies中添加依赖

def nav_version = "2.4.2"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"

2、在modle的build.gradle中的plugins代码块中添加下面的id

 id 'androidx.navigation.safeargs.kotlin'

3、在navigation.xml中添加参数标签<argument></argument>

<fragment
        android:id="@+id/verifyFragment"
        android:name="com.example.mykotlin2.VerifyDetailsFragment"
        android:label="fragment_verify_details"
        tools:layout="@layout/fragment_verify_details" >
        <argument android:name="name"
            app:argType="string"
            android:defaultValue='""'/>

        <argument android:name="mobile"
            app:argType="long"
            android:defaultValue="0L"/>

    </fragment>

4、build--->rebuild项目,自动生成代码

5、EnterDetailsFragment发送数据

findNavController().navigate(
                        EnterDetailsFragmentDirections
                            .actionExampleFragmentToVerifyFragment(
                                firstName,
                                mobile.toLong()
                            )
                    )

6、VerifyDetailsFragment接收数据

  val args :VerifyDetailsFragmentArgs by navArgs()
        val name = args.name
        val mobileNumber = args.mobile

        etName.setText(name)
        etMobileNumber.setText(mobileNumber.toString())

运行结果:

在该界面数据数据并点击按钮发送

在该界面接收数据并显示

 

 

注:

project的build.gradle

buildscript {

    repositories {
        google()
        jcenter()
        mavenCentral()

    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.30"

        def nav_version = "2.4.2"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }

}

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.3' apply false
    id 'com.android.library' version '7.1.3' apply false
    id 'org.jetbrains.kotlin.android' version '1.5.30' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

module的build.gradle

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'androidx.navigation.safeargs.kotlin'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.mykotlin2"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.6.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    def fragment_version = "1.4.1"
    //kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"

    implementation 'androidx.navigation:navigation-fragment-ktx:2.4.2'
    implementation 'androidx.navigation:navigation-ui-ktx:2.4.2'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'


    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

在navigation.xml中VerifyDetailsFragment中添加<argument>标签,有几个参数添加几个

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/navigation"
    app:startDestination="@id/exampleFragment">

    <fragment
        android:id="@+id/exampleFragment"
        android:name="com.example.mykotlin2.EnterDetailsFragment"
        android:label="fragment_enter_details"
        tools:layout="@layout/fragment_enter_details" >
        <action
            android:id="@+id/action_exampleFragment_to_verifyFragment"
            app:destination="@id/verifyFragment" />
    </fragment>
    <fragment
        android:id="@+id/verifyFragment"
        android:name="com.example.mykotlin2.VerifyDetailsFragment"
        android:label="fragment_verify_details"
        tools:layout="@layout/fragment_verify_details" >
        <argument android:name="name"
            app:argType="string"
            android:defaultValue='""'/>

        <argument android:name="mobile"
            app:argType="long"
            android:defaultValue="0L"/>

    </fragment>
</navigation>

在Enterfragment中发送数据:

package com.example.mykotlin2

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController


class EnterDetailsFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val rootView = inflater.inflate(R.layout.fragment_enter_details, container, false)

        val etName = rootView.findViewById<EditText>(R.id.et_first_name)
        val etMobileNumber = rootView.findViewById<EditText>(R.id.et_first_mobile)


        val btVerifyDetails = rootView.findViewById<Button>(R.id.btn_verify_details)
        btVerifyDetails.setOnClickListener{

            val firstName = etName.text.toString()
            val mobile = etMobileNumber.text.toString()

            when{
                firstName.isEmpty() -> {
                    Toast.makeText(activity,"Enter Name.",Toast.LENGTH_SHORT).show()
                }

                mobile.isEmpty() -> {
                    Toast.makeText(activity,"Enter Mobile.",Toast.LENGTH_SHORT).show()
                }

                else -> {
//                    val bundle = bundleOf(
//                        "name" to firstName,
//                        "mobile" to mobile.toLong()
//                    )
//                    findNavController()
//                        .navigate(R.id.action_exampleFragment_to_verifyFragment,
//                        bundle)

                    findNavController().navigate(
                        EnterDetailsFragmentDirections
                            .actionExampleFragmentToVerifyFragment(
                                firstName,
                                mobile.toLong()
                            )
                    )
                }
            }


//            findNavController().navigate(R.id.action_exampleFragment_to_verifyFragment)
        }

        return rootView
    }

}

在VerifyDetailsFragment中添加数据并显示

package com.example.mykotlin2

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController


class EnterDetailsFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val rootView = inflater.inflate(R.layout.fragment_enter_details, container, false)

        val etName = rootView.findViewById<EditText>(R.id.et_first_name)
        val etMobileNumber = rootView.findViewById<EditText>(R.id.et_first_mobile)


        val btVerifyDetails = rootView.findViewById<Button>(R.id.btn_verify_details)
        btVerifyDetails.setOnClickListener{

            val firstName = etName.text.toString()
            val mobile = etMobileNumber.text.toString()

            when{
                firstName.isEmpty() -> {
                    Toast.makeText(activity,"Enter Name.",Toast.LENGTH_SHORT).show()
                }

                mobile.isEmpty() -> {
                    Toast.makeText(activity,"Enter Mobile.",Toast.LENGTH_SHORT).show()
                }

                else -> {
//                    val bundle = bundleOf(
//                        "name" to firstName,
//                        "mobile" to mobile.toLong()
//                    )
//                    findNavController()
//                        .navigate(R.id.action_exampleFragment_to_verifyFragment,
//                        bundle)

                    findNavController().navigate(
                        EnterDetailsFragmentDirections
                            .actionExampleFragmentToVerifyFragment(
                                firstName,
                                mobile.toLong()
                            )
                    )
                }
            }


//            findNavController().navigate(R.id.action_exampleFragment_to_verifyFragment)
        }

        return rootView
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值