在Kotlin中的片段中使用按钮在片段之间切换,可以通过以下步骤实现:
<Button
android:id="@+id/switchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Switch to Fragment B" />
class FragmentA : Fragment() {
private lateinit var switchButton: Button
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_a, container, false)
switchButton = view.findViewById(R.id.switchButton)
switchButton.setOnClickListener {
val fragmentB = FragmentB()
val transaction = requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragmentContainer, fragmentB)
transaction.addToBackStack(null)
transaction.commit()
}
return view
}
}
class FragmentB : Fragment() {
private lateinit var backButton: Button
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_b, container, false)
backButton = view.findViewById(R.id.backButton)
backButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack()
}
return view
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragmentA = FragmentA()
supportFragmentManager.beginTransaction()
.add(R.id.fragmentContainer, fragmentA)
.commit()
}
}
通过以上步骤,你就可以在Kotlin中的片段中使用按钮在片段之间进行切换了。点击FragmentA中的按钮将会切换到FragmentB,点击FragmentB中的按钮将会返回到FragmentA。
领取专属 10元无门槛券
手把手带您无忧上云