【问题标题】:unreachable statement after using .getActivity( ) in a Fragment在 Fragment 中使用 .getActivity() 后无法访问的语句
【发布时间】:2015-04-04 15:18:13
【问题描述】:

我想在片段中使用 .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);
}

【问题讨论】:

  • 您的问题:return inflater.inflate(R.layout.newnode_layout, container,false);。不要从互联网上复制代码。请理解它的作用。

标签: android android-studio fragment


【解决方案1】:

你的方法的第一行有一个 return 语句,就在你的注释行的正上方 //GPS SIGNAL...

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

【讨论】:

  • 我又傻又瞎。感谢您的快速答复!
  • 没问题!我每天都感到愚蠢和盲目,所以你并不孤单。
【解决方案2】:

您必须将所有代码放在 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多