首页 > 解决方案 > 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
    }




}

标签: kotlin

解决方案


在您的代码中,您没有告诉 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 替换上述代码中的活动。


推荐阅读