在Fragment中调用getSystemServices时未定义? [英] getSystemServices is undefined when called in a Fragment?

查看:63
本文介绍了在Fragment中调用getSystemServices时未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望TextViewsFragment中显示传感器读数. eclipse说,当尝试初始化SensorManager时,getSystemServicesFragment中未定义.为什么以及如何修复它.

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扩展了ContextFragment没有扩展.因此,您首先需要获取包含FragmentActivity的引用,然后神奇地检索所需的系统服务.

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时未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆