如何从 Fragment.kt 文件调用 Activity?

0 android android-intent android-fragments kotlin

class ProfileFragment : Fragment() {
    private lateinit var tvhelpcenter: TextView
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_profile, container, false)
        /*  val view = inflater?.inflate(
              R.layout.fragment_home,
              container, false
          )*/
        /*val tv_help_center: TextView? = view?.findViewById(R.id.tv_help_center)
        tv_help_center!!.setOnClickListener {
            requireActivity().run {
                startActivity(Intent(this, HelpCenterActivity::class.java))
                finish()
            }
        }*/
    }
}
Run Code Online (Sandbox Code Playgroud)

Int*_*iya 5

您应该在这里使用activity!!而不是这个

对于片段使用 ->activity!!

 activity!!.startActivity(Intent(activity!!, HelpCenterActivity::class.java))
 finish()
Run Code Online (Sandbox Code Playgroud)

第二种方法

   (activity as MainActivityName)?.let{
       val intent = Intent (it, HelpCenterActivity::class.java)
       it.startActivity(intent)
       finish()
    }
Run Code Online (Sandbox Code Playgroud)

let-> 将调用它的对象作为参数并返回 lambda 表达式的结果。

it->关键字包含里面属性的副本let