只有第一张图是在ViewPager多SupportMapFragment展示 [英] Only first map is showing with Multiple SupportMapFragment in ViewPager

查看:159
本文介绍了只有第一张图是在ViewPager多SupportMapFragment展示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我有三个片段一viewpager。所有片段,使用取决于应用程序设置的自定义地图布局或ListView相同片段类的新实例。但问题只在地图模式。

问题

我每次在地图模式开始viewpager活动目前唯一的片段显示在地图上。其他的片段是空的。貌似所有的片段使用地图的唯一实例。而当前片段先得到这张地图。在其他两个片段地图是空的。


    

<的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直>    <包括
            布局=@布局/ loading_component/>    <的FrameLayout
            机器人:ID =@ + ID / mapFragmentHole
            机器人:layout_width =match_parent
            机器人:layout_height =match_parent
            机器人:layout_alignParentBottom =真
            机器人:layout_alignParentLeft =真
            机器人:layout_alignParentRight =真
            机器人:layout_alignParentTop =真
            机器人:layout_gravity =center_vertical | CENTER_HORIZONTAL/>    <按钮
            机器人:ID =@ + ID / cur_location
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:背景=@绘制/ map_compas
            机器人:layout_alignParentRight =真/>
    <按钮
            机器人:ID =@ + ID / go_back
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_alignParentBottom =真
            机器人:文字颜色=@彩色/ gray_theatre
            机器人:TEXTSIZE =21sp
            机器人:文字样式=大胆
            机器人:背景=@绘制/ go_to_list_button_bg
            机器人:文字=@字符串/ return_to_list
            机器人:layout_alignParentRight =真
            机器人:知名度=水涨船高/>< / RelativeLayout的>

SectionsPagerAdapter

公共类SectionsPagerAdapter扩展FragmentPagerAdapter {        公共SectionsPagerAdapter(FragmentManager FM){
            超(FM);
        }        @覆盖
        公众诠释getItemPosition(Object对象){
            返回POSITION_NONE;
        }        @覆盖
        公共片段的getItem(int i)以{
            如果(我== 0){
                返回CinemaAllFragment.newInstance(modeFavourite);
                //返回新CinemaFavouriteFragment();            }
            如果(ⅰ== 1){
                返回CinemaAllFragment.newInstance(modeOnline);
            }
            如果(ⅰ== 2){
                返回CinemaAllFragment.newInstance(modeDefault);
            }
            返回null;
        }        @覆盖
        公众诠释的getCount(){
            返回3;
        }        @覆盖
        公共CharSequence的getPageTitle(INT位置){
            开关(位置){
            情况下0:
                返回的getString(R.string.frame_cinema_title1);
            情况1:
                返回的getString(R.string.frame_cinema_title2);
            案例2:
                返回的getString(R.string.frame_cinema_title4);
            }
            返回null;
        }
    }

我的片段

公共类CinemaAllFragment扩展CinemaFragment实现LocationListener的{
私人的LocationManager的LocationManager;
私人字符串供应商;
私人GoogleMap的地图= NULL;私人标记myPosition;
私人查看气球;私人按钮curLocationBtn;保护的ListView listViewCinemas = NULL;
受保护的视图视图;私人字符串fragmentMode;
私人静态字符串MODE =模式;
私人静态字符串modeFavourite =modeFavourite;
私人静态字符串modeOnline =modeOnline;
私人静态字符串modeDefault =modeDefault;
私人影院[]电影院;
私人长期录入;
私人长期LASTUPDATE;
私人CinemaListArrayAdapter适配器= NULL;私有静态字符串片段=位置;私人的ArrayList<标志物GT;标记;私人长期nowTime;//处理程序更新UI timeFr,进度条等,。
私人处理程序mHandler =新的处理程序();
私人的Runnable onEveryFiveMinutes;私人SupportMapFragment supportMapFragment = NULL;公共静态的newInstance CinemaAllFragment(字符串someString)
{
    CinemaAllFragment myFragment =新CinemaAllFragment();
    捆绑ARGS =新包();
    args.putString(MODE,someString);
    myFragment.setArguments(参数);    返回myFragment;
}@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState)
{
    super.onCreateView(充气器,容器,savedInstanceState);    如果(getArguments()!= NULL)
        fragmentMode = getArguments()的getString(MODE,NULL);    如果(Settings.getCinemaTypeView()== Settings.CinemaTypeView.Map)
    {
        mLog.d(OnCreate中:图+ fragmentMode);        鉴于= inflater.inflate(R.layout.cinema_map,集装箱,FALSE);        。GoogleMapOptions GMO =(新GoogleMapOptions())zoomControlsEnabled(真).rotateGesturesEnabled(假);        如果(supportMapFragment == NULL)
            supportMapFragment = SupportMapFragment.newInstance(GMO);        FragmentTransaction fragmentTransaction = getActivity()getSupportFragmentManager()调用BeginTransaction()。
        fragmentTransaction.add(R.id.mapFragmentHole,supportMapFragment);
        fragmentTransaction.commit();        气球= inflater.inflate(R.layout.cinema_list_item,NULL);        ImageView的分隔符=(ImageView的)balloon.findViewById(R.id.delimiter);
        delimiter.setVisibility(View.GONE);    }
    否则如果(Settings.getCinemaTypeView()== Settings.CinemaTypeView.Listing)
    {
        鉴于= inflater.inflate(R.layout.cinema_list,集装箱,FALSE);
    }    返回视图。
}@覆盖
公共无效onResume(){
    super.onResume();    如果(Settings.getCinemaTypeView()== Settings.CinemaTypeView.Map)
    {
        setUpMapIfNeeded();
    }    的onUpdate();
}@覆盖
公共无效onDestroyView(){
    super.onDestroyView();
    如果(Settings.getCinemaTypeView()== Settings.CinemaTypeView.Map)
    {
        FragmentTransaction英尺= getActivity()getSupportFragmentManager()调用BeginTransaction()。
        ft.remove(supportMapFragment);
        ft.commit();
    }
}@覆盖
公共无效onActivityCreated(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onActivityCreated(savedInstanceState);
}类CustomInfoAdapter实现GoogleMap.InfoWindowAdapter {    @覆盖
    公共查看getInfoContents(标记标记){
        displayView(标记);        如果(!marker.getTitle()。等于(Я))
        {
            返回气球;
        }
        否则返回NULL;
    }    @覆盖
    公共查看getInfoWindow(标记标记){
        返回null;
    }
}公共无效displayView(标记标记){    TextView的cinema_title =(TextView中)balloon.findViewById(R.id.cinema_title);    电影院看电影= MoviesDbAdapter.getCinemaById(marker.getTitle());    如果(电影!= NULL)
    {
        cinema_title.setText(cinema.title);
    }
}公共无效checkGPSEnabled()
{
    //获取位置管理器
    的LocationManager =(的LocationManager) view.getContext().getApplicationContext().getSystemService(view.getContext().getApplicationContext().LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER / *提供商* /,0,0,这一点);    启用布尔=的LocationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);    //检查是否启用,如果不发送用户普惠制设置
    //更好的解决办法是显示一个对话框,并建议到
    //转到设置
    如果(!启用){
        新AlertDialog.Builder(view.getContext()。getApplicationContext())
                .setMessage(view.getContext().getApplicationContext().getResources().getString(R.string.message_gps_off))
                .setPositiveButton(view.getContext().getApplicationContext().getResources().getString(R.string.dialog_gps_enable),新DialogInterface.OnClickListener(){                    公共无效的onClick(DialogInterface对话,诠释它){
                        // TODO自动生成方法存根
                        意向意图=新意图(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(意向,5);
                    }
                })
                .setNegativeButton(view.getContext().getApplicationContext().getResources().getString(R.string.dialog_gps_cancel),新DialogInterface.OnClickListener(){                    公共无效的onClick(DialogInterface对话,诠释它){                    }
                })
                。显示();
    }}
/ *请求更新在启动* /@覆盖
公共无效onLocationChanged(地点){
    INT纬度=(int)的(location.getLatitude());
    INT经度=(int)的(location.getLongitude());
}@覆盖
公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
    // TODO自动生成方法存根}@覆盖
公共无效onProviderEnabled(字符串提供商){
    //的getLocation();
}@覆盖
公共无效onProviderDisabled(字符串提供商){
}/ **
 *设定地图,如果它是可以这样做(即谷歌Play服务APK是正确的
 *安装)和地图尚未实例化的。这将确保我们只有永远
 *调用{@link #setUpMap()}一次,{@link #map}不为空。
 *所述p为H.;
 *如果没有安装{@link SupportMapFragment}(和
 * {@link com.google.android.gms.maps.MapView
 *的MapView})将显示用户安装一个提示/更新谷歌APK上Play服务
 *他们的设备。
 *所述p为H.;
 *用户可以按照提示正确后,返回到该活动
 *安装/更新/启用谷歌播放服务。由于活动可能不是
 *在此过程中完全破坏(很可能将仅被停止或
 *暂停),{@link #onCreate(包)}可能不会被再次调用,所以我们应该调用此方法
 * {@link #onResume()},以保证它会被调用。
 * /
setUpMapIfNeeded私人无效(){
    //做一个空检查确认,我们还没有实例化地图。
    如果(图== NULL){
        //地图=(图形页面)getActivity()findViewById(R.id.map)。
        //尝试获取来自SupportMapFragment地图。
        地图= supportMapFragment.getMap();
        //map.setInfoWindowAdapter(new CustomInfoAdapter());        //检查是否成功地获得地图。
        如果(图!= NULL){
            setUpMap();
        }
    }
}私人无效的getLocation()
{    mLog.d(触摸);
    checkGPSEnabled();    地点= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER / * *供应商/);    //初始化位置字段
    如果(位置!= NULL){
        的System.out.println(提供者+提供商+已被选择。);
        CameraPosition CP =新CameraPosition.Builder()
                .TARGET(新经纬度(location.getLatitude(),location.getLongitude()))
                .zoom(12)
                。建立();
        map.animateCamera(CameraUpdateFactory.newCameraPosition(CP));        如果(myPosition!= NULL)
        {
            myPosition.remove();
        }
        myPosition = map.addMarker(新的MarkerOptions()
                .POSITION(新经纬度(location.getLatitude(),location.getLongitude()))
                .title伪(Я)
                .icon(BitmapDesc​​riptorFactory
                        .fromResource(R.drawable.map_marker_user)));
    }
}/ **
 *这是我们可以添加标记或线条,添加侦听器或移动相机。在这种情况下,我们
 *只需添加非洲附近的一个标记。
 *所述p为H.;
 *这应该只被调用一次,当我们确信{@link #map}不为空。
 * /
私人无效setUpMap(){
    map.setMyLocationEnabled(真);
    //map.getUiSettings().setMyLocationButtonEnabled(true);    //map.addMarker(new的MarkerOptions()位置(经纬度新(0,0))标题(标记))。;
}公共无效的onUpdate(){    如果(fragmentMode!= NULL)
    {
        如果(fragmentMode.equals(modeDefault)){
            电影院= MoviesDbAdapter.getCinemaAll();
        }
        否则,如果(fragmentMode.equals(modeFavourite))
        {
            电影院= MoviesDbAdapter.getCinemaFavorites();
        }
        否则,如果(fragmentMode.equals(modeOnline))
        {
            电影院= MoviesDbAdapter.getCinemaOnline();
        }
        mLog.d(OnCreate中:+ fragmentMode);
    }
    其他
    {
        电影院= MoviesDbAdapter.getCinemaAll();
    }    适配器=新CinemaListArrayAdapter(getActivity(),R.layout.movi​​es_list_item,电影院);    mLog.d(OnCreate中:的onUpdate+ fragmentMode);
    如果(cinemas.length == 0)
    {
        //加载进度
        //Utils.updateLoadingStatus(view,的getString(R.string.message_loading_cinemas));
    }    如果(Settings.getCinemaTypeView()== Settings.CinemaTypeView.Map)
    {
        尝试
        {
            checkGPSEnabled();
        }赶上(例外五){
            e.printStackTrace(); //改变catch语句使用文件的身体|设置|文件模板。
        }        // ApiDownloader下载=新ApiDownloader(getActivity()getApplicationContext());
        。//downloader.registerAPI(getActivity()getApplicationContext());        如果(标记!= NULL)
        {
            对于(标记标记:标记)
            {
                marker.remove();
            }
            Markers.clear();
        }        标记=新的ArrayList<标志物GT;();        如果(图!= NULL)
        {
            //нарисоватьмаркерыкинотеатров
            对于(影院电影:电影院)
            {
                //mLog.d(\"Cinema:+ cinema.getLatitude());
                标记cinemaMarker = map.addMarker(新的MarkerOptions()
                        .POSITION(新经纬度(Double.parseDouble(cinema.getLatitude()),Double.parseDouble(cinema.getLongitude())))
                        .title伪(cinema.getId()。的toString())
                        .icon(BitmapDesc​​riptorFactory
                                .fromResource(R.drawable.map_marker_mini)));                Markers.add(cinemaMarker);
            }
        }
    }
    其他
    {
        // ApiDownloader下载=新ApiDownloader(getActivity()getApplicationContext());
        。//downloader.registerAPI(getActivity()getApplicationContext());        listViewCinemas =(ListView控件)view.findViewById(R.id.cinemas_list_view);        INT索引= 0;
        视图V = NULL;
        如果(listViewCinemas!= NULL)
        {
            mLog.d(OnCreate中:列表非空+ fragmentMode ++ cinemas.length);            //保存指数和领先地位
            指数= listViewCinemas.getFirstVisiblePosition();
            V = listViewCinemas.getChildAt(0);
            INT顶部=(V == NULL)? 0:v.getTop();            listViewCinemas.setAdapter(适配器);
            listViewCinemas.setSelectionFromTop(指数,上图);            PauseOnScrollListener监听器=新PauseOnScrollListener(ImageLoader的,pauseOnScroll,pauseOnFling);
            listViewCinemas.setOnScrollListener(监听);        }
    }
}
}


解决方案

解决问题

刚刚分开地图功能片段和两个新的片段或者不进行映射。新的地图碎片从SupportMapFragment扩展,并允许他进行himlesf的观点:

 

 公共类CinemaMapFragment扩展SupportMapFragment实现LocationListener的{

...

 

  @覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState)
{
    鉴于= super.onCreateView(充气器,容器,savedInstanceState);
    气球= inflater.inflate(R.layout.cinema_list_item,NULL);
    返回视图。
}

然后添加我的自定义功能(只有两个按钮)编程:

 

  @覆盖
公共无效onResume(){
    super.onResume();    LayoutInflater吹气=(LayoutInflater)getActivity()getApplicationContext()getSystemService(Context.LAYOUT_INFLATER_SERVICE)。    查看VI = inflater.inflate(R.layout.location_button,NULL);
    查看VI2 = inflater.inflate(R.layout.golist_button,NULL);    curLocationBtn =(按钮)vi.findViewById(R.id.cur_location);
    goToList =(按钮)vi2.findViewById(R.id.go_back);    LinearLayout.LayoutParams的LayoutParams =新LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);    ((ViewGroup中)视图).addView(VI,的LayoutParams);    LinearLayout.LayoutParams layoutParams2 =新LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);    ((ViewGroup中)视图).addView(VI2,layoutParams2);

...

 

 私人无效setUpMapIfNeeded(){
    //做一个空检查确认,我们还没有实例化地图。
    如果(图== NULL){
        //地图=(图形页面)getActivity()findViewById(R.id.map)。
        //尝试获取来自SupportMapFragment地图。
        地图=的GetMap();
        map.setInfoWindowAdapter(新CustomInfoAdapter());        //检查是否成功地获得地图。
        如果(图!= NULL){
            setUpMap();
        }
    }
}

Background

I have a viewpager with three fragments. All the fragments are the new instance of the same fragment class that uses custom map layout or listview depending on the App Settings. But the problem only in map mode.

Problem

Every time I start viewpager activity in the map mode only current fragment shows the map. Other fragments are empty. Looks like all the fragments uses the only instance of map. And current fragment get this map first. Maps in other two fragments are null.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include
            layout="@layout/loading_component"/>

    <FrameLayout
            android:id="@+id/mapFragmentHole"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_gravity="center_vertical|center_horizontal" />

    <Button
            android:id="@+id/cur_location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/map_compas"
            android:layout_alignParentRight="true"/>
    <Button
            android:id="@+id/go_back"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:textColor="@color/gray_theatre"
            android:textSize="21sp"
            android:textStyle="bold"
            android:background="@drawable/go_to_list_button_bg"
            android:text="@string/return_to_list"
            android:layout_alignParentRight="true"
            android:visibility="gone"/>

</RelativeLayout>

SectionsPagerAdapter

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public Fragment getItem(int i) {
            if (i == 0) {
                return CinemaAllFragment.newInstance(modeFavourite);
                //return new CinemaFavouriteFragment();

            }
            if (i == 1) {
                return CinemaAllFragment.newInstance(modeOnline);
            }
            if (i == 2) {
                return CinemaAllFragment.newInstance(modeDefault);
            }
            return null;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return getString(R.string.frame_cinema_title1);
            case 1:
                return getString(R.string.frame_cinema_title2);
            case 2:
                return getString(R.string.frame_cinema_title4);
            }
            return null;
        }
    }

My Fragment

public class CinemaAllFragment extends CinemaFragment implements LocationListener {
private LocationManager locationManager;
private String provider;
private GoogleMap map = null;

private Marker myPosition;
private View balloon;

private Button curLocationBtn;

protected ListView listViewCinemas = null;
protected View view;

private String fragmentMode;
private static String MODE = "mode";
private static String modeFavourite = "modeFavourite";
private static String modeOnline = "modeOnline";
private static String modeDefault = "modeDefault";
private Cinema[] cinemas;
private Long updateTime;
private Long lastUpdate;


private CinemaListArrayAdapter adapter = null;

private static String FRAGMENT = "position";

private ArrayList<Marker> Markers;

private long nowTime;

// Handler to update UI timeFr, progress bar etc,.
private Handler mHandler = new Handler();
private Runnable onEveryFiveMinutes;

private SupportMapFragment supportMapFragment = null;

public static CinemaAllFragment newInstance(String someString)
{
    CinemaAllFragment myFragment = new CinemaAllFragment();
    Bundle args = new Bundle();
    args.putString(MODE, someString);
    myFragment.setArguments(args);

    return myFragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    super.onCreateView(inflater, container, savedInstanceState);

    if(getArguments()!=null)
        fragmentMode = getArguments().getString(MODE, null);

    if (Settings.getCinemaTypeView() == Settings.CinemaTypeView.Map)
    {
        mLog.d("OnCreate: map "+fragmentMode);

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

        GoogleMapOptions gmo = (new GoogleMapOptions()).zoomControlsEnabled(true).rotateGesturesEnabled(false);

        if(supportMapFragment == null)
            supportMapFragment = SupportMapFragment.newInstance(gmo);

        FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.mapFragmentHole, supportMapFragment);
        fragmentTransaction.commit();

        balloon = inflater.inflate(R.layout.cinema_list_item, null);

        ImageView delimiter = (ImageView) balloon.findViewById(R.id.delimiter);
        delimiter.setVisibility(View.GONE);

    }
    else if (Settings.getCinemaTypeView() == Settings.CinemaTypeView.Listing)
    {
        view = inflater.inflate(R.layout.cinema_list, container, false);
    }

    return view;
}

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

    if (Settings.getCinemaTypeView() == Settings.CinemaTypeView.Map)
    {
        setUpMapIfNeeded();
    }

    onUpdate();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    if (Settings.getCinemaTypeView() == Settings.CinemaTypeView.Map)
    {
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.remove(supportMapFragment);
        ft.commit();
    }
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
}

class CustomInfoAdapter implements GoogleMap.InfoWindowAdapter {

    @Override
    public View getInfoContents(Marker marker) {
        displayView(marker);

        if(!marker.getTitle().equals("Я"))
        {
            return balloon;
        }
        else return null;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }
}

public void displayView(Marker marker) {

    TextView cinema_title = (TextView) balloon.findViewById(R.id.cinema_title);

    Cinema cinema = MoviesDbAdapter.getCinemaById(marker.getTitle());

    if (cinema != null)
    {
        cinema_title.setText(cinema.title);
    }
}

public void checkGPSEnabled()
{
    // Get the location manager
    locationManager = (LocationManager) view.getContext().getApplicationContext().getSystemService(view.getContext().getApplicationContext().LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER/*provider*/, 0, 0, this);

    boolean enabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    // Check if enabled and if not send user to the GSP settings
    // Better solution would be to display a dialog and suggesting to
    // go to the settings
    if (!enabled) {
        new AlertDialog.Builder(view.getContext().getApplicationContext())
                .setMessage(view.getContext().getApplicationContext().getResources().getString(R.string.message_gps_off))
                .setPositiveButton(view.getContext().getApplicationContext().getResources().getString(R.string.dialog_gps_enable), new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, 5);
                    }
                })
                .setNegativeButton(view.getContext().getApplicationContext().getResources().getString(R.string.dialog_gps_cancel), new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

}
/* Request updates at startup */

@Override
public void onLocationChanged(Location location) {
    int lat = (int) (location.getLatitude());
    int lng = (int) (location.getLongitude());
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    //getLocation();
}

@Override
public void onProviderDisabled(String provider) {
}

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #map} is not null.
 * <p>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView
 * MapView}) will show a prompt for the user to install/update the Google Play services APK on
 * their device.
 * <p>
 * A user can return to this Activity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the Activity may not have been
 * completely destroyed during this process (it is likely that it would only be stopped or
 * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
 * {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (map == null) {
        //map = (MapView) getActivity().findViewById(R.id.map);
        // Try to obtain the map from the SupportMapFragment.
        map = supportMapFragment.getMap();
        //map.setInfoWindowAdapter(new CustomInfoAdapter());

        // Check if we were successful in obtaining the map.
        if (map != null) {
            setUpMap();
        }
    }
}

private void getLocation()
{

    mLog.d("Touch: ");
    checkGPSEnabled();

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER/*provider*/);

    // Initialize the location fields
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        CameraPosition cp = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(),location.getLongitude()))
                .zoom(12)
                .build();
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cp));

        if (myPosition != null)
        {
            myPosition.remove();
        }
        myPosition = map.addMarker(new MarkerOptions()
                .position(new LatLng(location.getLatitude(),location.getLongitude()))
                .title("Я")
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.map_marker_user)));
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p>
 * This should only be called once and when we are sure that {@link #map} is not null.
 */
private void setUpMap() {
    map.setMyLocationEnabled(true);
    //map.getUiSettings().setMyLocationButtonEnabled(true);

    //map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}

public void onUpdate() {

    if(fragmentMode != null)
    {
        if(fragmentMode.equals(modeDefault)){
            cinemas = MoviesDbAdapter.getCinemaAll();
        }
        else if (fragmentMode.equals(modeFavourite))
        {
            cinemas = MoviesDbAdapter.getCinemaFavorites();
        }
        else if (fragmentMode.equals(modeOnline))
        {
            cinemas = MoviesDbAdapter.getCinemaOnline();
        }
        mLog.d("OnCreate: "+fragmentMode);
    }
    else
    {
        cinemas = MoviesDbAdapter.getCinemaAll();
    }

    adapter = new CinemaListArrayAdapter(getActivity(), R.layout.movies_list_item, cinemas);

    mLog.d("OnCreate: onUpdate "+fragmentMode);
    if(cinemas.length == 0)
    {
        // Load schedules
        //Utils.updateLoadingStatus(view, getString(R.string.message_loading_cinemas));
    }

    if (Settings.getCinemaTypeView() == Settings.CinemaTypeView.Map)
    {
        try
        {
            checkGPSEnabled();
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        //ApiDownloader downloader = new ApiDownloader(getActivity().getApplicationContext());
        //downloader.registerAPI(getActivity().getApplicationContext());

        if (Markers != null)
        {
            for (Marker marker : Markers)
            {
                marker.remove();
            }
            Markers.clear();
        }

        Markers = new ArrayList<Marker>();

        if(map != null)
        {
            //нарисовать маркеры кинотеатров
            for (Cinema cinema : cinemas)
            {
                //mLog.d("Cinema: " + cinema.getLatitude());
                Marker cinemaMarker = map.addMarker(new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(cinema.getLatitude()),Double.parseDouble(cinema.getLongitude())))
                        .title(cinema.getId().toString())
                        .icon(BitmapDescriptorFactory
                                .fromResource(R.drawable.map_marker_mini)));

                Markers.add(cinemaMarker);
            }
        }
    }
    else
    {
        //ApiDownloader downloader = new ApiDownloader(getActivity().getApplicationContext());
        //downloader.registerAPI(getActivity().getApplicationContext());

        listViewCinemas = (ListView) view.findViewById(R.id.cinemas_list_view);

        int index = 0;
        View v=null;
        if(listViewCinemas != null)
        {
            mLog.d("OnCreate: list not null "+fragmentMode+" "+cinemas.length);

            // save index and top position
            index = listViewCinemas.getFirstVisiblePosition();
            v = listViewCinemas.getChildAt(0);
            int top = (v == null) ? 0 : v.getTop();

            listViewCinemas.setAdapter(adapter);
            listViewCinemas.setSelectionFromTop(index, top);

            PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
            listViewCinemas.setOnScrollListener(listener);

        }
    }
}
}

解决方案

Solve the issue

Just separate the fragment with map functionality and not map in two new fragments. The new map fragment extends from SupportMapFragment and allow him to make the view for himlesf:

public class CinemaMapFragment extends SupportMapFragment implements LocationListener {

...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    view = super.onCreateView(inflater, container, savedInstanceState);
    balloon = inflater.inflate(R.layout.cinema_list_item, null);
    return view;
}

Then I add my custom functionality (just two buttons) programmatically:

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

    LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View vi = inflater.inflate(R.layout.location_button, null);
    View vi2 = inflater.inflate(R.layout.golist_button, null);

    curLocationBtn = (Button) vi.findViewById(R.id.cur_location);
    goToList = (Button) vi2.findViewById(R.id.go_back);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    ((ViewGroup) view).addView(vi, layoutParams);

    LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);

    ((ViewGroup) view).addView(vi2, layoutParams2);

...

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (map == null) {
        //map = (MapView) getActivity().findViewById(R.id.map);
        // Try to obtain the map from the SupportMapFragment.
        map = getMap();
        map.setInfoWindowAdapter(new CustomInfoAdapter());

        // Check if we were successful in obtaining the map.
        if (map != null) {
            setUpMap();
        }
    }
}

这篇关于只有第一张图是在ViewPager多SupportMapFragment展示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆