getSystemServices is undefined when called in a Fragment?

拥有回忆 提交于 2019-11-30 12:39:18

问题


I want TextViews to display the sensors readings in a Fragment. When trying to initialize the SensorManager the getSystemServices is undefined in the Fragment, eclipse says.Why and how to fix it.

Fragment

public class FragSensors extends Fragment {

private TextView accXTv, accYTv, accZTv;
private SensorManager sensorManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View v = inflater.inflate(R.layout.frag_sensors, container, false);
    accXTv = (TextView) v.findViewById(R.id.accXValue);
    accYTv = (TextView) v.findViewById(R.id.accYValue);
    accZTv = (TextView) v.findViewById(R.id.accZValue);
    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

}

private final SensorEventListener mSensorListener = new SensorEventListener() {

    @Override
    public void onSensorChanged(SensorEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub

    }
};

}


回答1:


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.




回答2:


Use:

getActivity().getSystemService(name)



回答3:


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

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




回答4:


On Kotlin use:

this.sensorManager = activity!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager



回答5:


You can also get the context from the LayoutInflater.

SensorManager sm = (SensorManager) getLayoutInflater().getContext().getSystemService(Context.SENSOR_SERVICE);


来源:https://stackoverflow.com/questions/24427414/getsystemservices-is-undefined-when-called-in-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!