2015-10-18 31 views
3

我在Android開發人員相當新的,所以大家多多包涵。我遇到了一些實例狀態保存問題,我的谷歌地圖api實現我相信。我正在使用Android Studio。我正在實施AppCompactActivity來設置選項卡視圖。我正在使用FragmentStatePagerAdapter更改尋呼機視圖中的片段。我的問題是,我的谷歌地圖api不會在非常特定的情況下保存狀態。如果我點擊了遠離我的MapFragment索引的索引,那麼地圖片段的狀態將不會保留,並且我無法將標記或Go Home按鈕添加到地圖,但地圖存在。谷歌地圖碎片不節能狀態/不添加標記映射的onResume

我最初的標記和家庭住址按鈕的作品,它只是將不會顯示備份/讓我增加更多的指標後,我切換到我的最後一個標籤,並切換到地圖選項卡。

正如我所說的,我是新的Android開發人員,所以任何的建議是讚賞。

這是我的主要活動

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> 

回答

2

通過默認視圖尋呼機保持當前片段,並且它的左側和右側保存一個片段。在你的尋呼機適配器中,你告訴它創建一個全新的片段,而不是使用現有的片段。

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

啊啊啊!好。我無法找到任何有關狀態保存1索引的參考。我用其他人的標籤框架代碼,所以我認爲它是固有的,但我不知道如果我的第4個片段由於我內在的保存錯誤,或者如果我沒有保存,所以不保留狀態。謝謝!我會在這裏嘗試一下你的解決方案,並讓你知道我是否有任何問題。 –

+0

對不起,我現在剛剛回到這。你的答案奏效!非常感謝你。 –