android - Google Map Fragment 不保存状态/不会添加标记以映射 onResume

标签 android google-maps android-fragments

我是 Android 开发人员的新手,所以请多多包涵。我相信我的 google maps api 实现的实例状态保存存在一些问题。我正在使用安卓工作室。我正在实现 AppCompactActivity 来设置选项卡 View 。我正在使用 FragmentStatePagerAdapter 更改我的寻呼机 View 中的 fragment 。我的问题是我的 google maps api 在某些情况下不会保存状态。如果我单击距离我的 MapFragment 索引 >1 个索引的选项卡, map fragment 的状态将不会保留,我无法向 map 添加标记或“转到主页”按钮,但 map 存在。

我的初始标记和家庭位置按钮有效,只是不会显示备份/允许我在切换到最后一个选项卡并切换回 map 选项卡后添加更多标记。

正如我所说,我是 android 开发的新手,所以任何建议都是感激的。

这是我的主要 Activity

public class MainActivity extends AppCompatActivity{

    public static FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Map"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

}

主要 Activity xml 是这样的

<RelativeLayout
    android:id="@+id/main_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"/>

</RelativeLayout>

这是我的 PagerAdapter 类

public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return new TabFragment1();
            case 1:
                return new MapViewFragment();
            case 2:
                return new TabFragment2();
            case 3:
                return new TabFragment3();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

这是我的 MapFragment 类

public class MapViewFragment extends Fragment {

    private static View view;
    /**
     * Note that this may be null if the Google Play services APK is not
     * available.
     */

    private static GoogleMap mMap;
    private static Double latitude, longitude;
    private static String quickFilterText="";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }

        view = inflater.inflate(R.layout.activity_maps, container, false);

        // Passing harcoded values for latitude & longitude. Please change as per your need. This is just used to drop a Marker on the Map
        latitude = 26.78;
        longitude = 72.56;

        ImageButton arrowButton = (ImageButton) view.findViewById(R.id.arrowButton);
        arrowButton.setOnClickListener(new ImageButton.OnClickListener() {
            public void onClick(View newView) {
                RelativeLayout relLayout = (RelativeLayout) view.findViewById(R.id.filterDropDown);
                EditText text = (EditText) view.findViewById(R.id.quickFilter);
                try
                {
                    quickFilterText = text.getText().toString();
                }
                catch(Exception err)
                {

                }
                if(relLayout.getHeight()>0)
                {
                    relLayout.setLayoutParams(new RelativeLayout.LayoutParams(relLayout.getWidth(),0));
                }
                else
                {
                    relLayout.setLayoutParams(new RelativeLayout.LayoutParams(relLayout.getWidth(),180));
                }
            }
        });

        return view;
    }

    /***** Sets up the map if it is possible to do so *****/
    public void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null)
                setUpMap();
        }
    }
    /**
     * This is where we can add markers or lines, add listeners or move the
     * camera.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap}
     * is not null.
     */
    private static void setUpMap() {
        // For showing a move to my loction button
        mMap.setMyLocationEnabled(true);
        // For dropping a marker at a point on the Map
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"));
        // For zooming automatically to the Dropped PIN Location
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
                longitude), 12.0f));
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setUpMapIfNeeded();
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getChildFragmentManager()
                    .findFragmentById(map)).getMap(); // getMap is deprecated
            // Check if we were successful in obtaining the map.
            if (mMap != null)
                setUpMap();
        }
        setRetainInstance(true);
    }

    /**** The mapfragment's id must be removed from the FragmentManager
     **** or else if the same it is passed on the next time then
     **** app will crash ****/

    @Override
    public void onDestroy(){
        super.onDestroy();

    }
    @Override
    public void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }
}

这是我的 activity_maps.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment" />


    <RelativeLayout
        android:id="@+id/filterDropDown"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:background="#80000000"
        android:gravity="top|center"
        android:padding="4dp"
        android:weightSum="1">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:paddingLeft="8dp"
                    android:text="Filter"
                    android:id="@+id/filterTextBox"
                    android:gravity="center_vertical" />
                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/quickFilter"
                    android:paddingRight="8dp"
                    android:paddingLeft="8dp"
                    android:layout_toRightOf="@+id/filterTextBox" />
            </RelativeLayout>
        </RelativeLayout>

    <RelativeLayout
        android:id="@+id/arrow"
        android:layout_width="70dp"
        android:layout_height="23dp"
        android:orientation="horizontal"
        android:background="@drawable/shape"
        android:gravity="center"
        android:padding="4dp"
        android:layout_gravity="center_horizontal|top"
        android:weightSum="1"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/filterDropDown">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Filter"
            android:id="@+id/arrowButton"
            android:background="@drawable/down_arrow"
            android:clickable="true" />
    </RelativeLayout>
</RelativeLayout>

我的其他 3 个选项卡只是简单的 fragment ,里面有一个 TextView

public class TabFragment1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab_fragment_1, container, false);
    }
}

有布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab 1"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

最佳答案

默认情况下, View 分页器会保留当前 fragment ,以及它左右两侧的 fragment 。在您的寻呼机适配器中,您告诉它创建一个全新的 fragment ,而不是使用现有 fragment 。

List<Fragment> myPages; // populate this in the constructor
@Override
public Fragment getItem(int position) {
    return myPages.get(position);
}

@Override
public int getCount() {
    return myPages.size();
}

如果您知道您将永远只有这四个 fragment ,您还应该增加屏幕外页面限制。

viewPager.setOffscreenPageLimit(3);

如果在执行完这两件事后 map 遇到更多问题,您可能需要设置 map fragment 以保留其实例状态。覆盖 fragment 的 onCreate() 方法。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

关于android - Google Map Fragment 不保存状态/不会添加标记以映射 onResume,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193416/

相关文章:

android - PreferenceFragment - getPreferenceManager() 和 getPreferenceScreen() 之间的区别?

javascript - gMarker.key 未定义,它是必需的!! Angular 和谷歌地图应用程序中的错误

android - 可以在 Google map 上隐藏兴趣点吗?

android - 如何在滑动菜单中使用 Android Google Map V2 作为 fragment ?

android - Fragment 和 DialogFragment 之间的通信

java - 我可以将接口(interface)传递给 Fragment 包吗?

java - Android 中的 Activity 之间无法传递值

java - Android:使默认全息按钮不透明

android - 动态添加项目到 ScrollView 使其不滚动

android - 如何在新的 Google map 链接 URL 中控制我的方向类型偏好?