【发布时间】:2019-06-02 13:39:51
【问题描述】:
是否可以使用底部导航视图和导航组件在片段中传递和访问参数?
我正在使用具有多个片段的单一活动方法,其中我的顶级片段需要一个参数(通常通过 newInstance 生成的方法完成)。我查看了导航组件开发人员指南和代码实验室,但它只提到使用安全参数并在目的地和操作中添加参数标签。
这是我的导航图:
<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>
主活动:
override fun onCreate(savedInstanceState: Bundle?) {
...
val navController = Navigation.findNavController(this,
R.id.nav_host_fragment)
bottom_navigation.setupWithNavController(navController)
....
}
activity_main.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并使用不同的参数,还是它们总是只是固定值? -
是的,对于我的用例,我想在您点击底部导航时传递一些默认设置参数。我也可能在其他地方重用 homeFragment。
标签: android android-fragments bottomnavigationview android-jetpack android-architecture-navigation