使用底部导航视图和Navigation组件,在片段中传递和访问参数是否可行?
我正在使用一种活动和多个片段的方法,其中我的顶级片段需要一个参数(通常通过newInstance生成的方法完成)。我查看了Navigation组件开发人员指南和codelab,但它仅提到使用safeargs并在目标和操作中添加参数标记。
这是我的导航图:
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
app:startDestination="@id/homeFragment">
<fragment android:id="@+id/homeFragment"
android:name="uk.co.homeready.homeready.HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home">
<!--Do I create an argument block here?-->
</fragment>
<fragment android:id="@+id/calculatorFragment"
android:name="uk.co.homeready.homeready.CalculatorFragment"
android:label="fragment_calculator"
tools:layout="@layout/fragment_calculator"/>
<fragment android:id="@+id/resourcesFragment"
android:name="uk.co.homeready.homeready.ResourcesFragment"
android:label="fragment_resources"
tools:layout="@layout/fragment_resources"/>
</navigation>
底部导航视图菜单:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/homeFragment"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/title_home"/>
<item
android:id="@+id/calculatorFragment"
android:icon="@drawable/ic_baseline_attach_money_24px"
android:title="@string/title_calculator"/>
<item
android:id="@+id/resourcesFragment"
android:icon="@drawable/ic_baseline_library_books_24px"
android:title="@string/title_resources"/>
</menu>
MainActivity:
主活动:override fun onCreate(savedInstanceState: Bundle?) {
...
val navController = Navigation.findNavController(this,
R.id.nav_host_fragment)
bottom_navigation.setupWithNavController(navController)
....
}
主活动页面.xml
<android.support.constraint.ConstraintLayout>
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:layout_constraintBottom_toTopOf="@id/bottom_navigation"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph"/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation"
app:menu="@menu/bottom_navigation"/>
</android.support.constraint.ConstraintLayout>
主页片段
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val argument = //TODO access argument here
...
}
homeFragment
在从底部导航栏中点击它时始终带有一些默认的参数吗?你是否在其他地方重复使用了homeFragment
并使用不同的参数,还是它们总是固定的值? - ianhanniballake