ViewPager地图片段被加载两次

时间:2015-10-01 06:07:25

标签: android google-maps android-fragments android-viewpager

我在Activity_Homescreen中有一个视图寻呼机,并设置为FragmentPagerAdapteractivity有4个选项卡,寻呼机适配器使用相同的片段用于前三个选项卡,另一个片段用于选项卡布局中的最后一个选项卡。初始3个选项卡的片段有两个片段(映射和回收器视图)嵌套在那片段里面。

最初,当我使用应用时,片段正确加载,即,当我从 TAB 1 - > TAB 2 - > 标签3 。 但是当我回到 Tab 2 时,地图片段将不会显示任何标记。谷歌地图和回收者视图被正确加载但只有标记不可见。在调试时,我意识到片段是加载两次。从 TAB 4 TAB 3 之后出现。

如果有人能够尽快发布解决方案,那就太棒了。谢谢。

Activity_Homescreen.java

private Toolbar toolbar;
private DrawerLayout drawerLayout;
private TabLayout tabLayout;
private SearchView searchView;
private boolean searchSubmitted = false;
private NetworkInfo activeNetworkInfo;
private Homescreen_Pojo pojoInstance = Homescreen_Pojo.getInstance();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_homescreen);
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    pojoInstance.setActiveNetworkInfo(activeNetworkInfo);
    pojoInstance.setAdvancedSearchSubmitted(false);
    pojoInstance.setSearchSubmitted(false);

    setupToolbar();
    setupTabLayout();
    setupNavigationDrawer();
    setupNavigationItems();
    setupViewPager();
}

@Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {

    super.onPostCreate(savedInstanceState, persistentState);
}


public void setupToolbar() {
    toolbar = (Toolbar) findViewById(R.id.toolBar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    toolbar.setLogo(R.drawable.header_logo);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
}

private void setupNavigationDrawer() {
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
    drawerLayout.setDrawerListener(drawerToggle);
    drawerToggle.syncState();
}

private void setupNavigationItems() {
    final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
    TextView userNameCtrl = (TextView) navigationView.findViewById(R.id.navigation_userName);
    ImageView userImageCtrl = (ImageView) navigationView.findViewById(R.id.navigation_userImage);
    String userName = UserCredentials.getInstance().getUserName();
    String userPhotoUrl = UserCredentials.getInstance().getUserPhotoUrl();
    if (userName != null && userPhotoUrl != (null)) {
        userNameCtrl.setText(userName);
        new LoadImage(userImageCtrl).execute(userPhotoUrl);
    }
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            CharSequence menuItemTitle = menuItem.getTitle();
            if (Objects.equals(menuItemTitle, "Rate App")) {
                final String appPackageName = getPackageName();
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                } catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                }
            } else {
                Activity_Login.integration.logout();
                Intent intent = new Intent(getApplicationContext(), Activity_Login.class);
                startActivity(intent);
            }
            drawerLayout.closeDrawers();
            return true;
        }
    });
}

private void setupTabLayout() {
    tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setTabMode(TabLayout.MODE_FIXED);

    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.near_me_hover).setTag(1));
    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.all_hostels).setTag(2));
    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.top_five).setTag(3));
    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.advanced_search).setTag(4));
}

private void setupViewPager() {
    PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setOffscreenPageLimit(1);
    viewPager.setAdapter(pagerAdapter);
    pojoInstance.setViewPager(viewPager);
}

public boolean isInternetConnected() {
    boolean connection = true;
    activeNetworkInfo = pojoInstance.getActiveNetworkInfo();
    if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
        connection = false;
    }
    return connection;
}


@Override
protected void onResume() {
    final ViewPager viewPager = pojoInstance.getViewPager();
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            switch (tab.getPosition()) {
                case 0:
                    viewPager.setCurrentItem(tab.getPosition());
                    tab.setIcon(R.drawable.near_me_hover);
                    break;
                case 1:
                    viewPager.setCurrentItem(tab.getPosition());
                    tab.setIcon(R.drawable.all_hostels_hover);
                    break;
                case 2:
                    viewPager.setCurrentItem(tab.getPosition());
                    tab.setIcon(R.drawable.top_five_hover);
                    break;
                case 3:
                    viewPager.setCurrentItem(tab.getPosition());
                    tab.setIcon(R.drawable.advanced_search_hover);
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            switch (tab.getPosition()) {
                case 0:
                    tab.setIcon(R.drawable.near_me);
                    break;
                case 1:
                    tab.setIcon(R.drawable.all_hostels);
                    break;
                case 2:
                    tab.setIcon(R.drawable.top_five);
                    break;
                case 3:
                    tab.setIcon(R.drawable.advanced_search);
                    break;
            }

        }

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

        }
    });
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            tabLayout.getTabAt(position).select();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    super.onResume();
}

public void infoClick(MenuItem menuItem) {
    AlertDialog.Builder builder = new AlertDialog.Builder(Activity_HomeScreen.this);
    LayoutInflater inflater = LayoutInflater.from(getApplication());
    View infoView = inflater.inflate(R.layout.homescreen_toolbar_info, null);
    builder.setView(infoView);
    builder.setCancelable(true);
    builder.setIcon(R.drawable.launcher_icon);
    builder.setNeutralButton("Ok, got it", null);
    builder.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_home_screen, menu);
    final MenuItem searchItem = menu.findItem(R.id.search);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView = null;
    if (searchItem != null) {
        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(true);
        searchView.setSubmitButtonEnabled(false);
        searchView.setQueryHint("Place / Hostel Name");
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toolbar.setBackgroundColor(R.drawable.header_searchview);
            }
        });
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                searchView.onActionViewCollapsed();
                toolbar.setBackgroundResource(R.drawable.header_bg);

                return true;
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Homescreen_Pojo.getInstance().setUserQuery(query);
                pojoInstance.setSearchSubmitted(true);
                Intent intent = new Intent(Activity_HomeScreen.this, Activity_SimpleSearchView.class);
                startActivity(intent);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    return id == R.id.action_settings || super.onOptionsItemSelected(item);
}

}

PagerAdapter.java

@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            return new Fragment_Tabs_CommonUI();
        case 1:
            return new Fragment_Tabs_CommonUI();
        case 2:
            return new Fragment_Tabs_CommonUI();
        case 3:
            return new Fragment_Tab4();
    }
    return null;
}

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

}

Fragment for first 3 tabs


 @Nullable
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    int num = Homescreen_Pojo.getInstance().getViewPager().getCurrentItem();
    tabView = inflater.inflate(R.layout.tab_common_ui, container, false);
    if (Homescreen_Pojo.getInstance().isSearchSubmitted()) {
        setUserVisibleHint(true);
    }
    return tabView;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    int number = Homescreen_Pojo.getInstance().getViewPager().getCurrentItem();
    if (isVisibleToUser) {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (status == ConnectionResult.SUCCESS) {
            FragmentManager fragmentManager = getChildFragmentManager();
            MapFragment mapFragment = new MapFragment();
            CardList_Fragment listFragment = new CardList_Fragment();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(R.id.map_container, mapFragment);
            transaction.add(R.id.cardlist_container, listFragment);
            transaction.commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();

        } else {
            Snackbar.make(tabView, "GooglePlay Service not available !!", Snackbar.LENGTH_LONG).show();
        }
    }
}


}

MapFragment

public MapFragment() {
    super();
}

@Override
public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
    View v = super.onCreateView(arg0, arg1, arg2);
    initializeMap();
    return v;
}

private void initializeMap() {
    GPS_Tracker gpsTracker = new GPS_Tracker(getActivity());
    googleMap = getMap();
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googleMap.setMyLocationEnabled(true);
    googleMap.getUiSettings().setZoomControlsEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
    googleMap.getUiSettings().setCompassEnabled(true);
    googleMap.getUiSettings().setRotateGesturesEnabled(true);
    googleMap.getUiSettings().setZoomGesturesEnabled(true);
    googleMap.getUiSettings().setScrollGesturesEnabled(true);
    googleMap.getUiSettings().setTiltGesturesEnabled(true);

    LatLng technoparkLocation = new LatLng(8.55765, 76.88092);
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(technoparkLocation, 15));

    double userLatitude = gpsTracker.getLatitude();
    double userLongitude = gpsTracker.getLongitude();
    pojoInstance.setUserLatitude(userLatitude);
    pojoInstance.setUserLongitude(userLongitude);
    LatLng userLocation = new LatLng(userLatitude, userLongitude);
    googleMap.addMarker(new MarkerOptions().position(userLocation).title("User Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.map_userlocation)));
}

public void addMarkers(final ArrayList<Hostel> hostelList, Context mContext) {
    this.mapContext = mContext;
    for (Hostel hostel : hostelList) {
        Marker marker;
        if (hostel.getHostelType().equals("gents")) {
            marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(hostel.getHostelLatitude(), hostel.getHostelLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_gents)).title(hostel.getName()).snippet(hostel.getPlace()));
        } else if (hostel.getHostelType().equals("ladies")) {
            marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(hostel.getHostelLatitude(), hostel.getHostelLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_ladies)).title(hostel.getName()).snippet(hostel.getPlace()));
        } else {
            marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(hostel.getHostelLatitude(), hostel.getHostelLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_family)).title(hostel.getName()).snippet(hostel.getPlace()));
        }
        String markerTitle = marker.getTitle();
        infoWindowHashMap.put(markerTitle, hostel);
        showHostelInMap.put(markerTitle, marker);
        pojoInstance.setInfoWindowHashMap(infoWindowHashMap);
        pojoInstance.setShowInMap(showHostelInMap);
    }
    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            if (infoWindowHashMap.containsKey(marker.getTitle())) {
                Hostel hostel = infoWindowHashMap.get(marker.getTitle());
                Intent hostelIntent = new Intent(mapContext, Activity_HostelDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                hostelIntent.putExtra("hostelObj", hostel);
                mapContext.startActivity(hostelIntent);
            }
        }
    });
}

public void highlightMarker(Hostel hostel) {
    if (pojoInstance.getInfoWindowHashMap().containsValue(hostel)) {
        String title = hostel.getName();
        HashMap<String, Marker> hashMap = pojoInstance.getShowInMap();
        if (hashMap.containsKey(title)) {
            Marker marker = (Marker) hashMap.get(title);
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()), 250, null);
            marker.showInfoWindow();
        }
    }
}


}

RecylerView Fragment

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.cardlist_fragment, container, false);
    RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.rv);
    ImageView noResults = (ImageView) rootView.findViewById(R.id.no_results);
    TextView noResultsText = (TextView) rootView.findViewById(R.id.no_results_text);
    recyclerView.setVisibility(View.VISIBLE);
    noResults.setVisibility(View.GONE);
    noResultsText.setVisibility(View.GONE);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    Homescreen_Pojo.getInstance().setRecyclerView(recyclerView);
    Homescreen_Pojo.getInstance().setNoResultsText(noResultsText);
    Homescreen_Pojo.getInstance().setNoResultsImage(noResults);
    HostelDetailsManager manager = new HostelDetailsManager(getContext(), recyclerView);
    manager.jsonRequest(APIcontroller.getInstance().getURL());
    return rootView;
}

}

0 个答案:

没有答案