I tried to start an Activity from a fragment (with setOnClickListener), but it doesn't work. I start this fragment from an Activity, in a FrameLayout :
btn.setOnClickListener {
supportFragmentManager.beginTransaction()
.replace(R.id.FrameLayout,
FirstFragment()
)
.commit()
}
Here is my fragment code:
class FirstFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?
): View {
return inflater . inflate (R.layout.fragment_first, container, false)
}
I searched a lot and found much code but nothing worked. Thank you in advance!
You have to try this:
after \\
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle? ): View {
val v:View inflater . inflate (R.layout.fragment_first, container, false)
val btnCallFragment = v.findViewById<Button>(R.id.btn)
btnCallFragment.setOnClickListener{
startActivity(Intent(activity,MainActivity::class.java))
} return v } }
You never start Activities from Fragments. The navigation control is Activity responsability.
To start any Component in Android you need a Intent.
Here find the official documentation:
https://developer.android.com/guide/components/fragments?hl=es#CommunicatingWithActivity
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.