Digant
Digant

Reputation: 11

How can I call an Activity from Fragment.kt file?

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()
            }
        }*/
    }
}

Upvotes: 0

Views: 1450

Answers (2)

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

You should use activity!! instead of this here.

For Fragment use -> activity!!

 activity!!.startActivity(Intent(activity!!, HelpCenterActivity::class.java))
 finish()

2nd Approach

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

let->takes the object it is invoked upon as the parameter and returns the result of the lambda expression.

it->keyword contains the copy of the property inside let.

Upvotes: 5

Anupam
Anupam

Reputation: 2853

  1. Call the parent Activity:

    val intent = Intent (getActivity(), Main::class.java) getActivity().startActivity(intent)

    1. or do like this

    activity?.let{ val intent = Intent (it, Main::class.java) it.startActivity(intent) }

Upvotes: 0

Related Questions