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

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

问题描述

我希望 TextViewsFragment 中显示传感器读数.当尝试初始化 SensorManager 时,getSystemServicesFragment 中未定义,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 扩展了 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天全站免登陆