我试图制作一个将转到另一个片段的按钮,但是,它显示了第一个片段上方的第二个片段,我确实需要这些片段的帮助,因为它是新的。
这是我的第一个片段代码:
class ToolsFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_tools, container, false)
val calcButton = root.findViewById<Button>(R.id.calc_button)
calcButton.setOnClickListener {
Log.d("ToolsFragment", "Calc Button Clicked")
val fragment = MarksCalc()
val fragmentManager = activity!!.supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.nav_host_fragment, fragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
return root
}
}
这是我的第二个片段
package com.example.itclubbeta
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
class MarksCalc : Fragment() {
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_marks_calc, container, false)
}
}
这是nav_host_fragment
<?xml version="1.0" encoding="utf-8"?>
<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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main_page">
<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" />
</androidx.constraintlayout.widget.ConstraintLayout>
答案 0 :(得分:1)
您实际上可以在导航图
中向片段添加操作示例:
<fragment
android:id="@+id/fragment_id_here"
android:name="fragment_name_here">
<action
android:id="@+id/your_main_fragment_id_to_your_next_fragment_id
app:destination="@id/id_of_the_next_fragment_to_display"/>
</fragment>
,现在您可以通过 findNavController
调用操作calcButton.setOnClickListener {
Log.d("ToolsFragment", "Calc Button Clicked")
findNavController().navigate(
R.id.your_main_fragment_id_to_your_next_fragment_id
)
}
在https://developer.android.com/guide/navigation/navigation-design-graph
上了解有关导航的更多信息