Issue
I'm new to Kotlin/Android development and I'm making an app to display quizzes. Recently I decided to begin using fragments. On my MainActivity which has three fragments, I'd like one to have a method of clicking a subject and being taken to that particular quiz activity.
Note, there is only one quiz activity, but the intents pass a variable to display the relevant data for the quiz.
I had correctly implemented this when this page was not a fragment but struggling to find a solution this time.
Subject Fragment:
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.financialapp.InformationPage
import com.example.financialapp.databinding.FragmentModuleBinding
import android.content.Intent
class ModuleFragment : Fragment(com.quizapp.R.layout.fragment_module) {
private var _binding: FragmentModuleBinding ? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentModuleBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val subjectOne = binding.tvEnglish
subjectOne.setOnClickListener {
sendIntent(0)
}
val subjectTwo = binding.tvGeography
subjectOne.setOnClickListener {
sendIntent(1)
}
val subjectThree = binding.tvHistory
subjectThree.setOnClickListener{
sendIntent(2)
}
...
}
private fun sendIntent(passedVariable: Int) {
val intent = Intent(this, SubjectPage::class.java)
intent.putExtra("subject", passedVariable)
startActivity(intent)
finish()
}
...
At present I have errors from Intent asking to create a function, same with finish().
Having looked through several tutorials I can't seem to see whether it's possible or not.
Solution
finish()
is actually called on activity so you can use requireActivity()
get hold of the hosting activity of your fragment & instead of using this
in Intent params you can use requireContext()
Example:
private fun sendIntent(passedVariable: Int) {
val intent = Intent(requireContext(), MainActivity::class.java)
intent.putExtra("subject", passedVariable)
startActivity(intent)
requireActivity().finish()
}
Answered By - Mayur Gajra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.