getSystemServices is undefined when called in a Fragment?

前端 未结 7 1718
醉酒成梦
醉酒成梦 2020-12-08 18:59

I want TextViews to display the sensors readings in a Fragment. When trying to initialize the SensorManager the getSystemService

相关标签:
7条回答
  • 2020-12-08 19:10
    sensorManager = (SensorManager) 
    requireActivity().getSystemService(Context.SENSOR_SERVICE);
    
    0 讨论(0)
  • 2020-12-08 19:12

    Just one more method call:

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);  
    

    Why that one extra method call?
    the getSystemService() method that provides access to system services comes from Context. An Activity extends Context, a Fragment does not. Hence, you first need to get a reference to the Activity in which the Fragment is contained and then magically retrieve the system service you want.

    0 讨论(0)
  • 2020-12-08 19:13

    Use:

    getActivity().getSystemService(name)
    
    0 讨论(0)
  • 2020-12-08 19:15

    For kotlin this is what worked for me.

    private fun hideKeyboard() {
            val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (inputManager.isAcceptingText) {
                inputManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, 0)
            }
        }
    
    0 讨论(0)
  • 2020-12-08 19:18

    On Kotlin use:

    this.sensorManager = activity!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager
    
    0 讨论(0)
  • 2020-12-08 19:23
    sensorManager = (SensorManager) getActivity().getSystemService(Context.NAMEOF_SERVICE);
    

    Fragments cannot directly call System Services , You have to use Activity with which these Fragment is Attached

    0 讨论(0)
提交回复
热议问题