问题描述
我希望 TextViews
在 Fragment
中显示传感器读数.当尝试初始化 SensorManager
时,getSystemServices
在 Fragment
中未定义,eclipse 说.为什么以及如何修复它.
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.
片段
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
}
};
}
推荐答案
再调用一个方法:
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
为什么要调用一个额外的方法?
提供对系统服务的访问的 getSystemService()
方法来自 Context
.Activity
扩展了 Context
,Fragment
没有.因此,您首先需要获得对包含 Fragment
的 Activity
的引用,然后神奇地检索您想要的系统服务.
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.
这篇关于在 Fragment 中调用 getSystemServices 时未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!