Issue
I have the following code and am getting an error with the Intent. It is because of the this I am fairly certain.
btnsignup.setOnClickListener{
val intent = Intent(
this, signup::class.java
)
startActivity(intent)
}
btnlogin.setOnClickListener{
val intent = Intent(
this, login::class.java
)
startActivity(intent)
}
I tried
btnsignup.setOnClickListener{
val intent = Intent(
applicationContext, signup::class.java
)
startActivity(intent)
}
btnlogin.setOnClickListener{
val intent = Intent(
applicationContext, login::class.java
)
startActivity(intent)
}
Solution
In Android, this keyword refers to the current object (in this case, the click listener), not the Activity context required for starting an activity. That's why using this inside a click listener causes an error.
Try doing this:
btnsignup.setOnClickListener {
val intent = Intent(requireContext(), SignupActivity::class.java)
startActivity(intent)
}
btnlogin.setOnClickListener {
val intent = Intent(requireContext(), LoginActivity::class.java)
startActivity(intent)
}
or replace requireContext()
with requireActivity()
.
Using requireContext()
ensures that you get the context of the fragment, and using requireActivity()
ensures that you get the context of the parent activity when inside a fragment.
Answered By - Afaq Khan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.