Reputation:
How can I open a new activity with a button inside the fragment layout?.
I have tried this
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_home, container, false)
button25.setOnClickListener {
val intent = Intent (getActivity(), settingActivity::class.java)
getActivity().startActivity(intent)
}
return view
}
Any idea of how I can start a new activity inside a fragment?
Upvotes: 0
Views: 4073
Reputation: 133
Make your button's listener after your fragment view is created, which gives callback in onViewCreated
onCreateView is called when Fragment's view is in the process of creating and you are accessing your fragment view's child before creating it.
It should be done like,
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button25.setOnClickListener {
activity?.let{
val intent = Intent (it, Main::class.java)
it.startActivity(intent)
}
}
}
Upvotes: 3