I tried to make a stopwatch in Android Studios. I know how to make it on an activity, but I need to do it on a fragment. My problem is that I don't know how to setContentView in fragments with binding.
Relevant Code:
class Stoppuhr : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_stoppuhr, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentStoppuhrBinding.inflate(layoutInflater)
setContentView(binding.root)//<---
binding.startStopButton.setOnClickListener { startStopTimer() }
binding.resetButton.setOnClickListener { resetTimer() }
serviceIntent = Intent(getActivity(), TimerService::class.java)
requireActivity().registerReceiver(updateTime, IntentFilter(TimerService.TIMER_UPDATED));
}}
Thanks in advance.
CodePudding user response:
Fragment
s don't use setContentView(id)
. They have an onCreateView
function that handles inflation, which you are already doing. You should be able to retrieve the binding in that function and return the view at the end like normal.
This link has a section on binding with fragments, about half way down the page.