android-fragments Android导航组件:在片段中传递值(参数)

z2acfund  于 2022-11-14  发布在  Android
关注(0)|答案(9)|浏览(252)

我做过的事:

我已经创建了导航抽屉活动,作为导航抽屉活动的更新新格式,根据新的Android架构,我使用**Navigation Component**结构获得了它。
下面是NavControllerNavigationUINavigationView代码,当我单击任何导航项目时,它是打开的片段。

DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
        R.id.nav_home, R.id.nav_profile, R.id.nav_privacy_policy,
        R.id.nav_terms, R.id.nav_contact_us, R.id.nav_share, R.id.nav_send)
        .setDrawerLayout(drawer)
        .build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);

这是针对nav_host_fragment的:

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/mobile_navigation" />

使用此navigation/mobile_navigation.xml进行导航

<?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/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_home"
        android:name="com.sohamerp.marsremedies.fragment.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/nav_profile"
        android:name="com.sohamerp.marsremedies.fragment.ProfileFragment"
        android:label="@string/menu_my_profile"
        tools:layout="@layout/fragment_profile" />

    <fragment
        android:id="@+id/nav_privacy_policy"
        android:name="com.sohamerp.marsremedies.fragment.PrivacyPolicyFragment"
        android:label="@string/menu_privacy_policy"
        tools:layout="@layout/fragment_privacy_policy" />

    <fragment
        android:id="@+id/nav_terms"
        android:name="com.sohamerp.marsremedies.fragment.TermsConditionFragment"
        android:label="@string/menu_terms"
        tools:layout="@layout/fragment_terms_condition" />

    <fragment
        android:id="@+id/nav_contact_us"
        android:name="com.sohamerp.marsremedies.fragment.ContactUsFragment"
        android:label="@string/menu_contact_us"
        tools:layout="@layout/fragment_terms_condition" />

</navigation>

我想做的事:

现在,我想在Fragment被调用时将一些值作为bundle(参数)传递给它。
场景:我有两个片段PrivacyPolicyFragmentTermsConditionsFragment,在这两个片段中,我只是在WebView中相应地打开链接。因此,当我单击Privacy Policy的菜单项时,我将传递一个与之相关的链接。
在这个新的结构navigation/mobile_navigation.xml中,如何传递参数?
有什么帮助吗?

gwbalxhn

gwbalxhn1#

所以我忘了浏览这个链接:定义目标参数
但这个答案对所有像我这样懒惰的人都有帮助:
在项目级别build.gradle中添加依赖项:

classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.1.0"

在应用级别build.gradle中应用插件:

apply plugin: "androidx.navigation.safeargs"

使用XML:预定义(静态)值:

在navigation**/navigation/移动的_navigation.xml**的xml文件中声明argument标签,如下所示,或者您可以通过此链接进行设计:

<fragment
    android:id="@+id/nav_privacy_policy"
    android:name="com.sohamerp.marsremedies.fragment.PrivacyPolicyFragment"
    android:label="@string/menu_privacy_policy"
    tools:layout="@layout/fragment_privacy_policy" >
    <argument
        android:name="privacyPolicyLink"
        app:argType="string"
        android:defaultValue="http://sohamerp.com/avo/avo_privacy_policy.html"/>
</fragment>

<fragment
    android:id="@+id/nav_terms"
    android:name="com.sohamerp.marsremedies.fragment.PrivacyPolicyFragment"
    android:label="@string/menu_terms"
    tools:layout="@layout/fragment_terms_condition" >
    <argument
        android:name="privacyPolicyLink"
        app:argType="string"
        android:defaultValue="http://sohamerp.com/avo/avo_privacy_policy.html"/>
</fragment>

现在你必须在你的Fragment中编写代码,如下所示:

if(getArguments() != null) {
    // The getPrivacyPolicyLink() method will be created automatically.
    String url = PrivacyPolicyFragmentArgs.fromBundle(getArguments()).getPrivacyPolicyLink();
}

希望对你和其他人有帮助。

v1l68za4

v1l68za42#

简单快速的解决方案:

在目的地之间传递参数

Bundle bundle = new Bundle();
bundle.putString("amount", amount);
Navigation.findNavController(view).navigate(R.id.confirmationAction, bundle);

和接收

TextView tv = view.findViewById(R.id.textViewAmount);
tv.setText(getArguments().getString("amount"));
ws51t4hk

ws51t4hk3#

在这种情况下,您可以使用

private NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
  // Create the Bundle to pass, you can put String, Integer, or serializable object
  Bundle bundle = new Bundle();
  bundle.putString("link","http://yourlink.com/policy");
  bundle.putSerializable("USER", user); // Serializable Object
  navController.navigate(R.id.nav_terms, bundle); // called fragment with agruments

如果有任何帮助,你可以回复它

sycxhyv7

sycxhyv74#

要将参数传递给其他片段/目的地,请使用安全参数来确保类型安全。就像@bromden所示,安全参数将为action所源自的每个片段/目的地生成一个类。然后,您可以将参数传递给actionaction将导航到片段。
在接收片段中,如果您的程式码是在Kotlin中,请说PrivacyFragmentnavArgs()属性委派使用来存取参数。例如:

val args: PrivacyFragmentArgs by navArgs()

要更好地了解这一点,请访问Pass data between destinations

kmb7vmvb

kmb7vmvb5#

在较新版本的Android Studio 3.2+中,需要在build.gradle文件中添加以下依赖项和插件

步骤-1

项目级别build.gradle 中添加依赖项

dependencies {
    classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5'
}

应用程序级别build.gradle 中应用插件

plugins {
    id 'androidx.navigation.safeargs' 
}

步骤2

1.在导航文件中,res/navigation/nav_graph.xml
1.在任何片段或具有action标记的内部片段中声明参数标记
1.清单项目
示例xml代码

<fragment
     android:id="@+id/nav_register"
     android:name="com.pd.demo.ui.profile.RegisterFragment"
     android:label="@string/title_register"
     tools:layout="@layout/fragment_register">
     <action
         android:id="@+id/action_nav_register_to_nav_verify_otp"
         app:destination="@id/nav_verify_otp">
         <argument
             android:name="mobile"
             app:argType="string" />
         <argument
             android:name="password"
             app:argType="string" />
     </action>
 </fragment>

步骤3

在Kotlin代码下面,将参数传递给目标片段

val bundle = bundleOf("mobile" to binding.etMobileNo.text.toString().trim())
Navigation.findNavController(binding.root).navigate(R.id.action_nav_register_to_nav_verify_otp, bundle)

第四步

在Kotlin代码下面,从源代码片段中获取bundle参数

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    mobileNo = arguments!!.getString("mobile").toString()
    password = arguments!!.getString("password").toString()
}

此代码将帮助

guz6ccqo

guz6ccqo6#

你可以实现NavigationView.OnNavigationItemSelectedListener然后做如下操作:

override fun onNavigationItemSelected(item: MenuItem): Boolean {
   drawer_layout.closeDrawers()

        if (item.itemId == nv_navigation_drawer_navigation_view.checkedItem?.itemId)
            return false

     Handler().postDelayed({
                when (item.itemId) {
                    R.id.nav_privacy_policy -> {
                           val action = FragmentDirections.actionFragmentToPrivacyFragment("Policy link")

                     findNavController().navigate(action)

                    }
                }
            }, DRAWER_NAVIGATION_DELAY)
  return true
    }

在xml中,您可以向接收片段添加参数,在本例中为

<fragment
    android:id="@+id/nav_privacy_policy"
    android:name=".fragment.PrivacyPolicyFragment"
    android:label="@string/menu_privacy_policy"
    tools:layout="@layout/fragment_privacy_policy">

    <argument
        android:name="policy"
        app:argType="string" />
</fragment>
k4emjkb1

k4emjkb17#

您也可以传递可序列化的对象、枚举值和基本型别的数组。例如:

enum class ObjectType : Serializable {
    FIRST, SECOND
}

然后,将参数添加到xml。

<fragment
        android:id="@+id/nav_profile"
        android:name="com.sohamerp.marsremedies.fragment.ProfileFragment"
        android:label="@string/menu_my_profile"
        tools:layout="@layout/fragment_profile" >

        <argument
            android:name="myObjectType"
            android:defaultValue="SECOND"
            app:argType="com.project.app.data.ObjectType" />
</fragment>

请注意,您应该指定完整的路径!

irtuqstp

irtuqstp8#

使用NavController NavGraph导航从起始目的地传递数据非常简单。我使用它来显示与订单标题关联的订单行:

private void showRepositionLinesFragment(AppObjects.RepOrderHeader orderHeader) {

    int number = orderHeader.getOrderNumber();
    String orderNumber = String.format("%06d",number);
    String createDate = orderHeader.getCreateDate();
    Globals.LogTrace(this, AppAlertDialog.DialogType.Info,
        "Navigate to FragRepoLines with orderNumber: " + orderNumber,false);
    NavController navController = NavHostFragment.findNavController(FragmentRepositionHeaders.this);
    Bundle bundle = new Bundle();
    bundle.putString(getString(R.string.arg_header_ordernumber),orderNumber);
    bundle.putString(getString(R.string.arg_repheader_createdate), createDate);
    navController.getGraph().findNode(R.id.FragRepoLines).setLabel(orderNumber + " " + createDate);
    navController.navigate(R.id.action_FragRepoHeaders_to_FragRepoLines,bundle);
}

从处理订单行的片段中获取数据变得更加复杂。用NavController getArguments()尝试了几个小时。最后这对我来说是有效的。
在开始片段中:

NavController navController = NavHostFragment.findNavController(this);
    // We use a String here, but any type that can be put in a Bundle is supported
    MutableLiveData<String> liveData = navController.getCurrentBackStackEntry()
        .getSavedStateHandle()
        .getLiveData(getString(R.string.arg_header_ordernumber));
    liveData.observe(getViewLifecycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(String s) {
            Globals.LogTrace(this, AppAlertDialog.DialogType.Info, "+++++++++  liveData changed -> " + s, false);
        }
    });

在目标片段中:

String arg = getString(R.string.arg_header_ordernumber);
    NavController navController = NavHostFragment.findNavController(this);
    NavBackStackEntry navBackStackEntry = navController.getCurrentBackStackEntry();
    if (navBackStackEntry != null) {
        SavedStateHandle savedStateHandle = navBackStackEntry.getSavedStateHandle();
        if (savedStateHandle != null) {
            savedStateHandle.set(arg, "000000");
        } else {
            Globals.LogTrace(this, AppAlertDialog.DialogType.Info,"savedStateHandle == null",false);
        }
    } else {
        Globals.LogTrace(this, AppAlertDialog.DialogType.Info,"navBackStackEntry == null",false);
    }

源代码:以编程方式与Navigation组件交互
我将navController.getPreviousBackStackEntry()更改为navController.getCurrentBackStackEntry()

qzlgjiam

qzlgjiam9#

我遇到了同样的问题,但我仍然无法使用片段方向传递参数。由于我需要在几个片段中使用值,我决定在主Activity中使用伴随对象。它可能不是最好的,但它解决了问题:类主要活动:应用程序组件活动(){

companion object{
        var myGlobalVar = "Example"
    }

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

然后,我可以通过导入它来访问它在所有片段中的值:

import myAppPackage.MainActivity.Companion.myGlobalVar

我不得不从我的navGraph中删除参数,但我仍然可以在后台访问它。

相关问题