gpt4 book ai didi

android - 导航图打开另一个 fragment

转载 作者:行者123 更新时间:2023-12-05 00:18:01 27 4
gpt4 key购买 nike

我有一个简单的应用程序,我试图通过单击按钮打开另一个 fragment 。

我的导航图

<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/app_navigation"
app:startDestination="@id/homeFragment">


<fragment
android:id="@+id/homeFragment"
android:name="com.mine.parsexml.HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home" >

<action
android:id="@+id/action_homeFragment_to_playerFragment"
app:destination="@id/playerFragment" />
</fragment>
<fragment
android:id="@+id/playerFragment"
android:name="com.mine.parsexml.PlayerFragment"
android:label="fragment_player"
tools:layout="@layout/fragment_player" />
</navigation>

这是我在 fragment 中的onClick

binding.playVideos.setOnClickListener {
HomeFragmentDirections.actionHomeFragmentToPlayerFragment()
}

这是 Activity 布局

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<androidx.fragment.app.FragmentContainerView
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:navGraph="@navigation/app_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

当我点击按钮时,播放器 fragment 不会打开。

最佳答案

你必须使用 NavController 并使用 action id

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

NavController navController = Navigation.findNavController(view);

binding.playVideos.setOnClickListener {

navController.navigate(R.id.action_homeFragment_to_playerFragment);

}

关于android - 导航图打开另一个 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70007113/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com