[英]Android Navigation Component : Pass value (arguments) in fragments
我创建了Navigation Drawer Activity ,更新了Navigation Drawer Activity 的新格式,根据新的 Android 架构,我通过Navigation Component结构得到了它。
带有NavController
和NavigationUI
的NavigationView
代码在下面,当我单击任何导航项时,它正在打开片段。
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 被调用时将一些值作为包(参数)传递。
场景:我有两个片段PrivacyPolicyFragment
和TermsConditionsFragment
,在这两个片段中,我只是相应地打开 WebView 内的链接。 所以当我点击Privacy Policy
的菜单项时,我会传递一个与之相关的链接。
在这个新结构navigation/mobile_navigation.xml
打开片段中,我怎样才能通过 arguments?
有什么帮助吗?
所以我忘了通过这个链接: 定义目的地参数
但是这个答案对像我这样的所有懒惰的人都有帮助:
在项目级build.gradle 中添加依赖项:
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.1.0"
在应用级build.gradle 中应用插件:
apply plugin: "androidx.navigation.safeargs"
在导航/navigation/mobile_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();
}
希望它会帮助你其他人。
要将参数传递给其他片段/目标,请使用确保类型安全的安全参数。 就像@bromden 所示,Safe Args 将为action
起源的每个片段/目的地生成一个类。 然后,您可以传递参数到action
导航到该片段。
在接收片段中,如果您的代码在 Kotlin 中,请说PrivacyFragment
,通过navArgs()
属性委托来访问参数。 IE
val args: PrivacyFragmentArgs by navArgs()
为了更好地理解这一点,请访问目的地之间的通行证数据
您可以实现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>
您还可以传递可序列化对象、枚举值和基本类型数组。 例如:
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>
请注意,您应该指定完整路径!
在这种情况下,您可以使用
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
如果有任何帮助,您可以回复它
使用 NavController NavGraph 导航从起始目的地传递数据非常简单。 我使用它来显示与订单 header 关联的订单行:
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);
}
来源: 以编程方式与导航组件交互
我将 navController.getPreviousBackStackEntry() 更改为 navController.getCurrentBackStackEntry()
在较新版本的 Android Studio 3.2+ 中,需要在 build.gradle 文件中添加以下依赖项和插件
第1步
在项目级build.gradle 中添加依赖项
dependencies {
classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5'
}
在App-Level build.gradle 中应用插件
plugins {
id 'androidx.navigation.safeargs'
}
第2步
示例 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 代码下方,从源片段获取包参数
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mobileNo = arguments!!.getString("mobile").toString()
password = arguments!!.getString("password").toString()
}
此代码将有所帮助
简单快速的解决方案:
在目的地之间传递参数
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"));
我遇到了同样的问题,但我仍然无法使用片段方向传递参数。 因为我需要在我的几个片段中使用值,所以我决定在我的主要活动中使用一个伴随对象。 它可能不是最好的,但它解决了问题: class MainActivity : AppCompatActivity() {
companion object{
var myGlobalVar = "Example"
}
override fun onCreate(savedInstanceState: Bundle?) {....
然后我可以通过导入它来访问它在我所有片段中的值:
import myAppPackage.MainActivity.Companion.myGlobalVar
我不得不从我的 navGraph 中删除参数,但我仍然可以在后台访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.