簡體   English   中英

Google地圖片段未保存狀態/不會添加標記以映射onResume

[英]Google Map Fragment not saving state/won't add markers to map onResume

我在Android開發方面相當新,所以請耐心等待。 我相信我的谷歌地圖api實現的實例狀態保存有一些問題。 我正在使用Android Studio。 我正在實現AppCompactActivity來設置選項卡視圖。 我正在使用FragmentStatePagerAdapter在尋呼機視圖中更改片段。 我的問題是我的谷歌地圖api在非常特殊的情況下不會保存狀態。 如果我單擊距離我的MapFragment索引> 1索引的選項卡,則不會保留地圖片段的狀態,並且我無法將標記或Go Home按鈕添加到地圖,但是地圖存在。

我的初始標記和家庭位置按鈕工作,它只是不會顯示備份/允許我添加更多標記后切換到我的上一個選項卡並切換回地圖選項卡。

正如我所說,我是android dev的新手,所以任何建議都是值得贊賞的。

這是我的主要活動

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);
    }

}

主要活動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個標簽只是簡單的片段,里面有文本視圖

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>

默認情況下,視圖尋呼機保留當前片段,並且其左側和右側的一個片段保持活動狀態。 在您的尋呼機適配器中,您告訴它創建一個全新的片段,而不是使用現有的片段。

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();
}

如果您知道只有這四個片段,您還應該增加屏幕外頁面限制。

viewPager.setOffscreenPageLimit(3);

如果在執行這兩項操作后遇到更多地圖問題,您可能需要設置地圖片段以保留其實例狀態。 覆蓋片段onCreate()方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM