2015-06-15 55 views
1

我有一個TabLayout與2個選項卡。 第一個選項卡(主選項卡)是列表視圖中的商店列表 第二個選項卡與Google地圖中的列表相同。加載谷歌地圖時選項卡被選中,而不是從開始

我注意到,當我默認在第一個標籤(列表)中出現時,GPS圖標出現在通知欄中。

事情是大部分的時間,用戶將使用名單,有沒有必要加載,所以我認爲是電池

我該怎麼做才能載入我的地圖上的那一刻,用戶單擊第二個的無用損耗標籤,而不是從初始化???

這裏是我的代碼:

public class FragmentTabsPdv extends BaseActivity { 

    private ArrayList<Pdv> listaPdv; 
    Adapter adapter; 
    ViewPager viewPager; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ctx = this; 
     setContentView(R.layout.tabs_pdv); 

     PdvHandler db = new PdvHandler(); 
     listaPdv = db.getAllTiendas(); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     final ActionBar ab = getSupportActionBar(); 
     adapter = new Adapter(getSupportFragmentManager()); 

     if (ab != null){ 
      ab.setDisplayShowTitleEnabled(false); 
      ab.setDisplayHomeAsUpEnabled(true); 
      ab.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp); 

     } 
     toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); 

     TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
     viewPager = (ViewPager) findViewById(R.id.viewpager); 

     if (viewPager != null) { 
      setupViewPager(viewPager); 
      tabLayout.setupWithViewPager(viewPager); 
     } 
     tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
      @Override 
      public void onTabSelected(TabLayout.Tab tab) { 
       if (tab.getText().equals("Mapa")){ 

       } 
      } 

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

      } 

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

      } 
     }); 

    } 

    public ArrayList<Pdv> getListaPdv() { 
     return listaPdv; 
    } 


    static class Adapter extends FragmentPagerAdapter { 
     private final List<Fragment> mFragments = new ArrayList<>(); 
     private final List<String> mFragmentTitles = new ArrayList<>(); 

     public Adapter(FragmentManager fm) { 
      super(fm); 
     } 

     public void addFragment(Fragment fragment, String title) { 
      mFragments.add(fragment); 
      mFragmentTitles.add(title); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      return mFragments.get(position); 
     } 

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

     @Override 
     public CharSequence getPageTitle(int position) { 
      return mFragmentTitles.get(position); 
     } 
    } 


    @Override 
    public void onBackPressed() { 
     setResult(RESULT_OK); 
     finish(); 

    } 

    private void setupViewPager(ViewPager viewPager) { 
     adapter.addFragment(new ListPdvTabFragment(), "Lista"); 
     adapter.addFragment(new Fragment(), "Mapa"); 
     viewPager.setAdapter(adapter); 


     } 

    } 

MapPdvFragment.java

public class MapPdvTabFragment extends Fragment implements GoogleMap.OnMarkerClickListener { 
private MapView mapView; 
private GoogleMap map; 
private ArrayList<Pdv> pdvs; 
private ViewPager pager; 
private View fragmentView; 
boolean showNoResults = false; 
SharedPreferences prefs; 
Context ctx; 
private Pdv currentPdv; 

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

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.tab_frag_map_pdv, container, false); 
    fragmentView = v; 

    Bundle localBundle = null; 
    if (savedInstanceState != null) 
     localBundle = savedInstanceState.getParcelable("mapViewBundle"); 

    // Gets the MapView from the XML layout and creates it 
    mapView = (MapView) v.findViewById(R.id.map); 

    // Gets to GoogleMap from the MapView and does initialization stuff 

    mapView.onCreate(localBundle); 
    mapView.onResume();// needed to get the map to display immediately 

    map = mapView.getMap(); 
    map.getUiSettings().setMyLocationButtonEnabled(false); 
    map.setOnMarkerClickListener(this); 

    MapsInitializer.initialize(this.getActivity()); 

    FragmentTabsPdv parent = (FragmentTabsPdv) getActivity(); 
    pdvs = parent.getListaPdv(); 

    // Updates the location and zoom of the MapView 
    map.setMyLocationEnabled(true); 
    int zoom = 14; 
    LatLng defaultLocation = null; 
    for (Pdv pdv : pdvs) { 
     if (pdv.getLatitude() != 0d) { 
      defaultLocation = new LatLng(pdv.getLatitude(), pdv.getLongitude()); 
      break; 
     } 
    } 
    if (defaultLocation == null || defaultLocation.latitude == 0.0d) { 
     defaultLocation = new LatLng(23.6266557, -102.5375005); 
     zoom = 5; 
    } 

    CameraUpdate here = CameraUpdateFactory.newLatLngZoom(defaultLocation, zoom); 
    map.moveCamera(here); 

    showNoResults = !(pdvs != null && pdvs.size() > 0); 

    initPager(); 

    map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() { 
     @Override 
     public void onInfoWindowClick(Marker marker) { 
      clickPdv(currentPdv); 

     } 
    }); 
    return v; 
} 

@Override 
public void onResume() { 
    mapView.onResume(); 
    super.onResume(); 
    PdvHandler db = new PdvHandler(); 
    pdvs = db.getAllTiendas(); 

    displayPdvOnMap(pdvs); // Display markers 
} 

@Override 
public void onPause() { 
    super.onPause(); 
    if (mapView != null) 
     mapView.onPause(); 
} 

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

@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    if (mapView != null) 
     mapView.onSaveInstanceState(outState); 
} 

@Override 
public void onLowMemory() { 
    super.onLowMemory(); 
    mapView.onLowMemory(); 
} 

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 

} 

public void displayPdvOnMap(ArrayList<Pdv> tiendas) { 
    map.clear(); 
    for (Pdv pdv : tiendas) { 
     Marker marker = map 
       .addMarker(new MarkerOptions() 
         .position(new LatLng(pdv.getLatitude(), pdv.getLongitude())) 
         .title(pdv.getTienda()).snippet(pdv.getCalle())); 

     if (pdv.getDone() == 1) 
      marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
     else 
      marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); 

     pdv.setMarker(marker); 
    } 
} 

public void initPager() { 

    pager = ((ViewPager) fragmentView.findViewById(R.id.pager)); 
    pager.setOffscreenPageLimit(3); 
    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
     public void onPageScrollStateChanged(int paramAnonymousInt) { 
     } 

     public void onPageScrolled(int paramAnonymousInt1, float paramAnonymousFloat, int paramAnonymousInt2) { 
     } 

     public void onPageSelected(int position) { 

      Pdv pdv = pdvs.get(position); 
      if (pdv.getLatitude() != 0d) { 
       Marker m = pdv.getMarker(); 
       m.showInfoWindow(); 
       // Center map on current marker 
       CameraUpdate here = CameraUpdateFactory.newLatLngZoom(m.getPosition(), 14); 
       map.animateCamera(here); 
       // TODO Esta siendo un poco pesado la animacion 
      } else { 
       Toast toast = Toast.makeText(getActivity(), 
         ctx.getString(R.string.tienda_no_geolocalizada),Toast.LENGTH_SHORT); 
       toast.setGravity(Gravity.CENTER, 0, 0); 
       toast.show(); 

      } 

     } 
    }); 
    pager.setSaveEnabled(false); 
    PagerAdapter pagerAdapter = new PagerAdapter() { 

     public void destroyItem(ViewGroup paramAnonymousViewGroup, 
           int paramAnonymousInt, Object paramAnonymousObject) { 
      paramAnonymousViewGroup.removeView((View) paramAnonymousObject); 
     } 

     public int getCount() { 

      if (showNoResults) 
       return 1; 
      if (pdvs != null) 
       return pdvs.size(); 
      return 0; 
     } 

     public Object instantiateItem(View container, int position) { 
      View view; 
      LayoutInflater li = (LayoutInflater) getActivity() 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      if (showNoResults) { 
       view = li.inflate(R.layout.map_pager_empty, null); 
      } else { 
       view = li.inflate(R.layout.row_lista_pdv, null); 
       final Pdv pdv = pdvs.get(position); 
       TextView tienda_name = (TextView) view.findViewById(R.id.tienda_name); 
       TextView direccion = (TextView) view.findViewById(R.id.tienda_dir); 

       String sucursal = pdv.getSucursal(); 
       String calle = pdv.getCalle(); 

       if (sucursal == null) { 
        sucursal = pdv.getTienda(); 
        if (sucursal == null) 
         sucursal = ctx.getString(R.string.sin_nombre); 
       } 

       if (calle == null) { 
        calle = pdv.getCiudad(); 
        if (calle == null) 
         calle = ctx.getString(R.string.sin_calle); 
       } 


       tienda_name.setText(sucursal); 
       direccion.setText(calle); 

      ((ViewPager) container).addView(view, 0); 
      return view; 
     } 

     public boolean isViewFromObject(View paramAnonymousView,Object paramAnonymousObject) { 
      return paramAnonymousView == paramAnonymousObject; 
     } 
    }; 
    this.pager.setAdapter(pagerAdapter); 

} 

/** 
* Manda a la captura o despliga infos de captura 
* 
* @param pdv el punto de venta actual 
*/ 
private void clickPdv(final Pdv pdv) { 
    ListPdvTabFragment lptf = new ListPdvTabFragment(); 
    lptf.openPdv(getActivity(), pdv, 0); 
} 

@Override 
public boolean onMarkerClick(Marker marker) { 
    int i; 
    i = getPdvPosition(marker); 
    currentPdv = pdvs.get(i); 

    if (i >= 0) 
     pager.setCurrentItem(i, true); 
    return false; 
} 

private int getPdvPosition(Marker marker) { 
    int position = 0; 
    for (Pdv pdv : pdvs) { 
     Marker m = pdv.getMarker(); 
     String mId1 = m.getId(); 
     String mId2 = marker.getId(); 
     if (mId1.equals(mId2)) { 
      return position; 
     } 
     position++; 
    } 
    return 0; 
} 

@Override 
public void onStart() { 
    super.onStart(); 
    prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
    String activityName = getClass().getSimpleName(); 
    prefs.edit().putString("FrontActivity", activityName).apply(); 
} 

}

回答

0

的FragmentPagerAdapter總是同時加載兩個你片段(因爲用戶可以Swype輸入下一個任何時候都可以使用),並且你不能使預加載的碎片數量少於2(每邊一個)。

如果您想要,您可以在用戶使用已覆蓋的onTabSelected回調登錄「Mapa」片段之後初始化映射。我想現在你已經在onCreate中完成了,只需要在Fragment可見之後調用的方法中移動它。

下面是一些代碼:

更改setupViewPager使你保持參照地圖片段:

private void setupViewPager(ViewPager viewPager) { 
     adapter.addFragment(new ListPdvTabFragment(), "Lista"); 
     //Add mMapaFragment as a member of the activity 
     mMapaFragment = new Fragment(); 
     adapter.addFragment(mMapaFragment, "Mapa"); 
     viewPager.setAdapter(adapter); 
    } 

然後在你的mMapaFragment調用setupMap方法,當它進入視圖。

 viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { 

     @Override 
     public void onPageSelected(int arg0) { 
      // Check if your "Mapa" Fragment is selected, it's probably on position one 
      if (arg0 == 1) { 
       mMapaFragment.setupMap(): 
      } 
     } 

     @Override 
     public void onPageScrolled(int arg0, float arg1, int arg2) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void onPageScrollStateChanged(int arg0) { 
      // TODO Auto-generated method stub 

     } 
    }); 

然後在setUpMap()方法中加載映射。

+0

我試圖重寫onTabSelected中的我的片段,但我沒有成功的結果...任何代碼建議? –

+0

我已經添加了一些到我的答案,我不能做更多,除非你把你的Mapa片段的代碼。 –

+0

我添加了Mapa Fragment代碼...我喜歡你的方法,但是我找不到在沒有在地圖片段中獲得NPE的情況下執行此操作的方法 –

相關問題