android - fragment 未附加到 FragmentManager

标签 android google-maps android-fragments

我尝试在显示为 fragment 的 googlemap 上显示我的位置。 fragment 布局代码为:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/window_background_color"
android:clickable="false">

<!-- Toolbar  -->

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:background="@color/primary_color"
    android:elevation="1dp"
    android:minHeight="?attr/actionBarSize"
    android:titleTextAppearance="@style/TextAppearance.AppCompat.Body1"
    app:popupTheme="@style/Theme.AppCompat">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:maxLines="1"
        android:text="@string/toolbar"
        android:textColor="@android:color/white"
        android:textSize="24sp" />
</androidx.appcompat.widget.Toolbar>

<RelativeLayout
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/toolbar"
    android:background="#1c3049"
    android:orientation="horizontal">

    <Button
        android:id="@+id/help"
        android:layout_width="45dp"
        android:layout_height="wrap_content"
        android:background="?attr/colorAccent"
        android:text="@string/help" />

    <Spinner
        android:id="@+id/spnCategory"
        android:layout_width="44dp"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:gravity="end" />

    <TextView
        android:id="@+id/mymess"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="95dp"
        android:gravity="center_vertical|center_horizontal"
        android:textColor="@android:color/white"
        android:textSize="14sp" />
</RelativeLayout>

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/test"
    android:orientation="vertical" />

fragment 显示在 mainActivity 中:

FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
ActivityMap mFragment = new ActivityMap();
mTransaction.add(R.id.fragment, mFragment);
mTransaction.commit();

我调用 getUserPosition 来自:

@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;
    getUserPosition(location.getLatitude(), location.getLongitude());
}

我的 getUserPosition 代码是:

  public void getUserPosition(double latitude, double longitude) {

    mCurrentLatitude = latitude;
    mCurrentLongitude = longitude;

    if (mIsMapVisible && isNetworkAvailable()) {
        TextView mytext = Objects.requireNonNull(getActivity()).findViewById(R.id.mymess));

        Geocoder geocoder = new Geocoder(getActivity(), Locale.ENGLISH);
        List<Address> addresses;
        try {
            addresses = geocoder.getFromLocation(mCurrentLatitude, mCurrentLongitude, 1);
            if ((addresses.size()>0)) {
                String str = addresses.get(0).getAddressLine(0);
                if(str.contains(",")) {
                    mytext.setText(str.substring(0, str.indexOf(",")));
                } else {
                    mytext.setText(str);
                }
            } else {
                mytext.setText(R.string.no_adr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
            String temp = mCurrentLatitude + "," + mCurrentLongitude;
            mytext.setText(temp);
        }
    }

    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
            new LatLng(mCurrentLatitude, mCurrentLongitude),
            Utils.ARG_DEFAULT_MAP_ZOOM_LEVEL);

    mMap.animateCamera(cameraUpdate);

}

最后这是问题部分:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getLayoutInflater().getContext().getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

这里我收到下一条错误消息:E/UncaughtException: java.lang.IllegalStateException: onGetLayoutInflater() cannot be executed until the Fragment is attached to the FragmentManager.

我第一次运行应用程序时完美无缺。第二次我得到错误。依此类推,直到我的设备询问是否要关闭应用程序,因为他停止继续。我接受并且下一次运行完美。然后……又是问题垃圾邮件。

有什么建议吗?

最佳答案

Fragments 有自己的生命周期。在处理 fragment 时,您始终应该考虑它们可能是分离的、隐藏的或者它们的状态已经保存。

问题的发生可能是因为您过早地收听了位置更改事件。但是,即使您在注册位置监听器时进行了更改,以安全的方式获取 Context(或 Activity)也是一种很好的做法(因为分离时,Context/Actvity 将为空)。

所以,我建议:

private boolean isNetworkAvailable() {
    boolean result = false;
    Context context = getContext();
    if(context != null) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
        result = activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    return result;
}

Fragment 有一个 getContext() 方法。因此,您可以将 getLayoutInflater() 替换为 getContext()

关于android - fragment 未附加到 FragmentManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292045/

相关文章:

swift - 为什么 xcode 尝试转换 googlemap cocoapods 框架?

php - 搜索到的地址与谷歌地图 api v3 上最近的现有地标之间的距离

android - 使用 SectionsPagerAdapter android

android - 为 ActionBarCompat 中的 fragment 调用 setDisplayHomeAsUpEnabled

Android多行EditText

android - D8 : Type `sun.misc.Unsafe` was not found

android - 为什么在大多数 Android 日志记录代码中使用 TAG

android - Collapsingtoolbarlayout中如何正确使用map fragment

android - 单击按钮更改 Fragment 上的文本

android - 替换具有相同包名称但新 keystore 的 Android 应用程序