kotlin - Kotlin:如何从片段导航到活动
问题描述
我正在尝试通过单击按钮从 Fragment 导航到活动。
我在网上搜索了很多次,但仍然无法解决问题..
我的应用程序因以下代码崩溃,有人可以看看发生了什么吗?
非常感谢您!
package com.gearsrun.www.UI.Home.fragment
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.gearsrun.www.R
import com.gearsrun.www.UI.Sunflower.SunflowerAvailableActivity
import kotlinx.android.synthetic.main.fragment_profile.*
class ProfileFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_profile, container, false)
btn_log_out.setOnClickListener {
activity?.let {
val intent = Intent(it,SunflowerAvailableActivity::class.java)
it.startActivity(intent)
}
}
return v
}
}
解决方案
在您的代码中,您没有告诉 btn_log_out 到底是什么?
编辑:
class ProfileFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_profile, container, false)
try{
//you need to be specific
val logoutBtn : Button = v.findViewById(R.id.btn_log_out)
// now use logoutBtn
logoutBtn.setOnClickListener {
activity?.let {
val intent = Intent(it,SunflowerAvailableActivity::class.java)
it.startActivity(intent)
}
}} catch(e:Exception){
Log.e("ProfileFragmentError", " Error", e)
}
return v
}
我相信这应该可行,如果不尝试用上下文或 requireContext() 或 requireActivity 替换上述代码中的活动。
推荐阅读
- python - Discord.py 添加反应
- javascript - 分配给变量的 innerHTML 不能实时更新?
- javascript - 循环遍历数组并将具有匹配参数的任何对象添加到新数组
- c - 从二叉搜索树中打印奇数级别的偶数计数
- image - 颤振缩放图像以填充高度而没有边界错误
- vb.net - 如何引用多个按钮?(VB.NET)
- javascript - `getComputedStyle` 返回什么以及如何对其进行迭代?
- ios - 在 SwiftUI 中处理双重和三重手势识别器
- reactjs - react useState 仅更新数组中的新值
- git - 将本地存储库与远程存储库的分支同步