片段中使用.getActivity()后无法访问的语句

时间:2015-02-04 22:19:18

标签: android android-studio fragment

我想在Fragment中使用.getSystemService。当我使用.getActivity()来获取我的活动的上下文时,Android Studio在同一行中告诉我这是一个"无法访问的语句"。

当我使用" getActivity()"的行上方有一行时,它会显示顶部的这一行无法访问。

为什么以及如何解决这个问题?

public class NewNodeFragment extends Fragment {

//GPS SIGNAL
double pLat;
double pLong;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.newnode_layout, container,false);

    //GPS SIGNAL
    LocationManager gpsmanager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    Location lastLocation = gpsmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (lastLocation != null) {
        pLat = lastLocation.getLatitude();
        pLong = lastLocation.getLongitude();
    }

    LocationListener gpslistener = new mylocationListener();
    gpsmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpslistener);
}

2 个答案:

答案 0 :(得分:12)

您的方法中的第一行有一个return语句,位于您的评论// GPS SIGNAL ...

的行的正上方

返回语句后的任何内容当然都是无法访问的代码。

答案 1 :(得分:5)

您必须将所有代码放在return语句之前。

public class NewNodeFragment extends Fragment {

//GPS SIGNAL
double pLat;
double pLong;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


    //GPS SIGNAL
    LocationManager gpsmanager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    Location lastLocation = gpsmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (lastLocation != null) {
        pLat = lastLocation.getLatitude();
        pLong = lastLocation.getLongitude();
    }

    LocationListener gpslistener = new mylocationListener();
    gpsmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpslistener);

    return inflater.inflate(R.layout.newnode_layout, container,false);
}