Android 在ViewPager中使用MapFragment的最佳方式是什么?

Android 在ViewPager中使用MapFragment的最佳方式是什么?,android,android-fragments,android-viewpager,google-maps-android-api-2,mapfragment,Android,Android Fragments,Android Viewpager,Google Maps Android Api 2,Mapfragment,我有一个带有两个选项卡的ViewPager,第一个选项卡是位置列表,第二个选项卡是位置地图。现在,我可以从数据库中填充列表,并让地图在应用程序的另一个位置工作,但我很难将它作为一个片段与选项卡布局一起工作 以下是我的地图片段的代码: import java.util.ArrayList; import android.annotation.SuppressLint; import android.content.Intent; import android.database.Cursor; i

我有一个带有两个选项卡的ViewPager,第一个选项卡是位置列表,第二个选项卡是位置地图。现在,我可以从数据库中填充列表,并让地图在应用程序的另一个位置工作,但我很难将它作为一个片段与选项卡布局一起工作

以下是我的地图片段的代码:

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapFragment extends Fragment implements OnInfoWindowClickListener,
        LoaderManager.LoaderCallbacks<Cursor> {

    MarkerOptions options = new MarkerOptions();
    LatLngBounds.Builder build = new LatLngBounds.Builder();
    GoogleMap map;

    double[] lats;
    double[] lngs;
    String[] names;
    String[] types;
    int count;
    int[] ids;

    // @Override
    // public View onCreateView(LayoutInflater inflater, ViewGroup container,
    // Bundle savedInstanceState) {
    // View v = (RelativeLayout) inflater.inflate(R.layout.dialog_map,
    // container, false);
    // setUpMapIfNeeded(null, null);
    // setupMarkers();
    // LatLngBounds bounds = build.build();
    // setUpMapIfNeeded(null, bounds);
    // return v;
    // }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // setContentView(R.layout.dialog_map);

        // setUpMapIfNeeded(null, null);

        // Prepare the loader. Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);
    }

    private void setupMarkers() {
        // get the passed crags names and locations
        // double[] lats = getArguments().getDoubleArray(ClimbProvider.LAT);
        // double[] lngs = getArguments().getDoubleArray(ClimbProvider.LONG);
        // ArrayList<String> names = getArguments().getStringArrayList(
        // ClimbProvider.NAME);
        // interate and add every passed crag to the map as a marker
        for (int i = 0; i < count; i++) {
            // add the crags name and location to the marker
            LatLng pos = new LatLng(lats[i], lngs[i]);
            options.position(pos);
            options.title((String) names[i]);
            // add the marker to the map
            map.addMarker(options);
            map.setOnInfoWindowClickListener(this);
            build.include(pos);
        }
    }

    private void setUpMapIfNeeded(MarkerOptions options,
            final LatLngBounds bounds) {
        if (options == null && bounds == null) {
            map = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
        } else if (bounds != null) {
            map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            map.getUiSettings().setZoomControlsEnabled(false);
            try {
                map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 70));
            } catch (IllegalStateException e) {
                // layout not yet initialised
                final View mapView = getFragmentManager().findFragmentById(
                        R.id.map).getView();
                if (mapView.getViewTreeObserver().isAlive()) {
                    mapView.getViewTreeObserver().addOnGlobalLayoutListener(
                            new OnGlobalLayoutListener() {

                                @SuppressWarnings("deprecation")
                                @SuppressLint("NewApi")
                                // We check which build version we are using.
                                @Override
                                public void onGlobalLayout() {
                                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                                        mapView.getViewTreeObserver()
                                                .removeGlobalOnLayoutListener(
                                                        this);
                                    } else {
                                        mapView.getViewTreeObserver()
                                                .removeOnGlobalLayoutListener(
                                                        this);
                                    }
                                    map.moveCamera(CameraUpdateFactory
                                            .newLatLngBounds(bounds, 70));
                                }
                            });
                }

            }
        }
    }

    // when an info bubble is clicked get its title and search for it in the
    // list of crag names the cross reference this with the list of crag ids and
    // pass that to the view crag activity
    @Override
    public void onInfoWindowClick(Marker marker) {
        int id = -1;
        for (int i = 0; i < count; i++) {
            if (names[i].contentEquals(marker.getTitle())) {
                id = ids[i];
            }
        }
        Intent viewCrag = new Intent(getActivity(), CragViewActivity.class);
        viewCrag.putExtra("id", id);
        Log.d("ClimbTrack", "row id = " + id);
        startActivity(viewCrag);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created. This
        // sample only has one Loader, so we don't care about the ID.
        // First, pick the base URI to use depending on whether we are
        // currently filtering.
        Uri allcrags = Uri
                .parse("content://com.fooforever.climbtrack.provider/crags");
        return new CursorLoader(getActivity(), allcrags, null, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        ArrayList<Double> latsArray = new ArrayList<Double>();
        ArrayList<Double> lngsArray = new ArrayList<Double>();
        ArrayList<Integer> idsArray = new ArrayList<Integer>();
        ArrayList<String> namesArray = new ArrayList<String>();
        ArrayList<String> typesArray = new ArrayList<String>();
        // Swap the new cursor in. (The framework will take care of closing the
        // old cursor once we return.)
        // mAdapter.swapCursor(data);
        // move to the top of the query results
        data.moveToFirst();
        // put all the ids from the result into a list so they can be
        // referenced against the listview item id
        while (data.isAfterLast() == false) {
            idsArray.add(data.getInt(data.getColumnIndex(ClimbProvider._ID)));
            latsArray
                    .add(data.getDouble(data.getColumnIndex(ClimbProvider.LAT)));
            lngsArray.add(data.getDouble(data
                    .getColumnIndex(ClimbProvider.LONG)));
            namesArray.add(data.getString(data
                    .getColumnIndex(ClimbProvider.NAME)));
            typesArray.add(data.getString(data
                    .getColumnIndex(ClimbProvider.TYPE)));
            data.moveToNext();
        }

        count = data.getCount();
        lats = new double[count];
        lngs = new double[count];
        names = new String[count];
        types = new String[count];
        ids = new int[count];
        convert_arr_double(latsArray, lats);
        convert_arr_double(lngsArray, lngs);
        convert_arr_string(namesArray, names);
        convert_arr_string(typesArray, types);
        convert_arr_int(idsArray, ids);

        // The list should now be shown.
        // if (isResumed()) {
        // setListShown(true);
        // } else {
        // setListShownNoAnimation(true);
        // }
        setupMarkers();
        LatLngBounds bounds = build.build();
        setUpMapIfNeeded(null, bounds);

    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        // TODO
    }

    // convert the passed arraylist to a double array
    private void convert_arr_double(ArrayList<Double> array, double[] out) {
        for (int i = 0; i < count; i++) {
            out[i] = array.get(i);
        }
    }

    private void convert_arr_string(ArrayList<String> array, String[] out) {
        for (int i = 0; i < count; i++) {
            out[i] = array.get(i);
        }
    }

    private void convert_arr_int(ArrayList<Integer> array, int[] out) {
        for (int i = 0; i < count; i++) {
            out[i] = array.get(i);
        }
    }
}
在setupmap ifneeded()函数的第88行第4/5行

The method getMap() is undefined for the type MapFragment

我不明白为什么这里会出现编译错误,这是实现这类功能的最佳方法吗?

使用
ViewPager
在列表和地图之间导航可能会产生一些令人沮丧的行为-尝试平移地图可能会导致视图切换,反之亦然

您可以使用普通选项卡导航(消除任何平移/视图切换障碍),也可以为地图视图实现“锁定”按钮以锁定平移

至于为什么会出现编译错误:

public class MapFragment extends Fragment implements OnInfoWindowClickListener,
    LoaderManager.LoaderCallbacks<Cursor> {
    ...
    map = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
}

“试图平移地图可能会导致切换视图,反之亦然”--子类
ViewPager
,覆盖
canScroll()
,并在那里指示地图上的触摸事件应转到地图。下面是一个示例应用程序,演示了这一点:对于可以触摸地图之外某个位置以启动对另一个页面的更改的页面,这是有效的;对于整个视图都是地图的页面,这会产生不一致的行为,不是吗?在列表中滑动可更改页面,但在地图上点击顶部的页面指示器可更改页面?“对于整个视图都是地图的页面,这会产生不一致的行为,不是吗?”--正确,我的示例多少说明了这一点,因为您可以更改页面的唯一方法是通过选项卡。然而,
ViewPager
仍然是一种比许多实现选项卡的替代方法(例如,
FragmentTabHost
)更灵活的方法。如果没有选项卡或等效项,占据整个页面的地图会使
ViewPager
毫无意义,因此这是一个UI设计缺陷。我不喜欢OP的UI设计(在一个页面中列出,在另一个页面中映射),因为这是对
ViewPager
和水平滑动的误用。感谢您的澄清;我担心我不知何故误解了
ViewPager
的工作原理。谢谢大家,我听说使用
ViewPager
可能会出现界面奇怪的情况(我没有想到),但我要试试看到底会发生什么。虽然更改类的名称对编译错误没有帮助,但我仍然得到相同的结果。。。有什么想法吗?
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
                R.id.map)).getMap();