Android - ListView中包含的MapView

时间:2010-06-02 20:15:43

标签: android listview android-mapview

目前我正在尝试在ListView中放置MapView。有人有这个成功吗?它甚至可能吗?这是我的代码:

            ListView myList = (ListView) findViewById(android.R.id.list);
        List<Map<String, Object>> groupData = new ArrayList<Map<String, Object>>();

        Map<String, Object> curGroupMap = new HashMap<String, Object>();
        groupData.add(curGroupMap);
        curGroupMap.put("ICON", R.drawable.back_icon);
        curGroupMap.put("NAME","Go Back");
        curGroupMap.put("VALUE","By clicking here");

        Iterator it = data.entrySet().iterator();
        while (it.hasNext()) 
        {
            //Get the key name and value for it
            Map.Entry pair = (Map.Entry)it.next();
            String keyName = (String) pair.getKey();
            String value = pair.getValue().toString();

            if (value != null)
            {
                //Add the parents -- aka main categories
                curGroupMap = new HashMap<String, Object>();
                groupData.add(curGroupMap);

                //Push the correct Icon
                if (keyName.equalsIgnoreCase("Phone"))
                    curGroupMap.put("ICON", R.drawable.phone_icon);
                else if (keyName.equalsIgnoreCase("Housing"))
                    curGroupMap.put("ICON", R.drawable.house_icon);
                else if (keyName.equalsIgnoreCase("Website"))
                    curGroupMap.put("ICON", R.drawable.web_icon);
                else if (keyName.equalsIgnoreCase("Area Snapshot"))
                    curGroupMap.put("ICON", R.drawable.camera_icon);
                else if (keyName.equalsIgnoreCase("Overview"))
                    curGroupMap.put("ICON", R.drawable.overview_icon);  
                else if (keyName.equalsIgnoreCase("Location"))
                    curGroupMap.put("ICON", R.drawable.map_icon);
                else
                    curGroupMap.put("ICON", R.drawable.icon);

                //Pop on the Name and Value
                curGroupMap.put("NAME", keyName);
                curGroupMap.put("VALUE", value);
            }
        }

        curGroupMap = new HashMap<String, Object>();
        groupData.add(curGroupMap);
        curGroupMap.put("ICON", R.drawable.back_icon);
        curGroupMap.put("NAME","Go Back");
        curGroupMap.put("VALUE","By clicking here");

        //Set up adapter
        mAdapter = new SimpleAdapter(
                mContext,
                groupData,
                R.layout.exp_list_parent,
                new String[] { "ICON", "NAME", "VALUE" },
                new int[] { R.id.photoAlbumImg, R.id.rowText1, R.id.rowText2  }
        );

        myList.setAdapter(mAdapter); //Bind the adapter to the list 

先谢谢你的帮助!!

5 个答案:

答案 0 :(得分:56)

将一个替代解决方案发布到一个相当古老的答案(实际上超过2年),但我认为这可能会帮助那些可能像我一样偶然发现这篇文章的人。

注意:对于只需要在“地图”中显示位置但不需要在ListView中与其进行交互的人来说,这可能很有用。点击ListView

中的项目后,可以在详细信息页面上显示实际地图

正如@CaseyB已经指出的那样,MapView是一种沉重的看法。为了对抗这个方面(并且让我的生活更轻松但更容易;-)),我选择像使用静态Google Map一样构建一个URL,使用我的应用程序所需的几个参数。您可以在此处获得更多选项:https://developers.google.com/maps/documentation/staticmaps/

首先,当我为ListView构建数据时,我将纬度经度等数据传递给带有一些静态变量的字符串从上面提到的链接。我从Facebook API获得了我的坐标。

我用来构建链接的代码:

String getMapURL = "http://maps.googleapis.com/maps/api/staticmap?zoom=18&size=560x240&markers=size:mid|color:red|"  
+ JOLocation.getString("latitude") 
+ "," 
+ JOLocation.getString("longitude") 
+ "&sensor=false";

上述构造的URL在浏览器中使用时会返回.PNG文件。然后,在我的adapter活动中,我使用@ Fedor的延迟加载来显示从之前构建的URL生成的图像,以显示在自定义ListView中。您当然可以选择自己的方法来显示Map(实际上是地图的图像)。

最终结果的一个例子。

enter image description here

目前,我在这个ListView中有大约30个奇怪的Checkin Maps(我将它与Facebook SDK一起使用),但是用户可以拥有100个,并且绝对没有关于它减速的报告。

我怀疑,考虑到问题已经过去的时间,这可能无法帮助OP,但希望它能帮助其他用户在将来登陆此页面。

答案 1 :(得分:6)

首先,我不认为一次显示多个MapView会起作用。 MapActivity文档每个进程只支持一个:

“每个进程只支持一个MapActivity。同时运行的多个MapActivities可能会以意外和不受欢迎的方式干扰。”

http://code.google.com/android/add-ons/google-apis/reference/index.html

它没有明确表示你不能在MapActivity中拥有多个MapView,但我认为它们也会干涉,无论它们属于哪种父ViewGroup。

其次,您可以考虑使用静态地图API来获取包含在ListView中的简单图像 - 在任何情况下,完全成熟的MapView都可能是不必要的重量级:

http://code.google.com/apis/maps/documentation/staticmaps/

您可能面临的一个问题是静态地图API限制了“用户”的使用,这可能意味着通过IP(它不需要API密钥),并且移动网络可能会因IP使用限制而出现问题。我不确定这究竟是怎么发生的。

答案 2 :(得分:5)

在这种情况下,您可以像使用任何其他视图一样将MapView添加到列表中。 Here's a quick tutorial了解如何创建自定义列表适配器。但是我必须提醒你,MapView是一个相当沉重的视图,如果你试图在屏幕上获得一堆它们,你会注意到应用程序缓慢!您可以只在列表项中添加一个按钮,将用户带到另一个页面,其中包含更多信息,包括地图。

答案 3 :(得分:3)

可以从GoogleMapSample代码中获取:

/**
 * This shows to include a map in lite mode in a ListView.
 * Note the use of the view holder pattern with the
 * {@link com.google.android.gms.maps.OnMapReadyCallback}.
 */
public class LiteListDemoActivity extends AppCompatActivity {

    private ListFragment mList;

    private MapAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.lite_list_demo);

        // Set a custom list adapter for a list of locations
        mAdapter = new MapAdapter(this, LIST_LOCATIONS);
        mList = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.list);
        mList.setListAdapter(mAdapter);

        // Set a RecyclerListener to clean up MapView from ListView
        AbsListView lv = mList.getListView();
        lv.setRecyclerListener(mRecycleListener);

    }

    /**
     * Adapter that displays a title and {@link com.google.android.gms.maps.MapView} for each item.
     * The layout is defined in <code>lite_list_demo_row.xml</code>. It contains a MapView
     * that is programatically initialised in
     * {@link #getView(int, android.view.View, android.view.ViewGroup)}
     */
    private class MapAdapter extends ArrayAdapter<NamedLocation> {

        private final HashSet<MapView> mMaps = new HashSet<MapView>();

        public MapAdapter(Context context, NamedLocation[] locations) {
            super(context, R.layout.lite_list_demo_row, R.id.lite_listrow_text, locations);
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewHolder holder;

            // Check if a view can be reused, otherwise inflate a layout and set up the view holder
            if (row == null) {
                // Inflate view from layout file
                row = getLayoutInflater().inflate(R.layout.lite_list_demo_row, null);

                // Set up holder and assign it to the View
                holder = new ViewHolder();
                holder.mapView = (MapView) row.findViewById(R.id.lite_listrow_map);
                holder.title = (TextView) row.findViewById(R.id.lite_listrow_text);
                // Set holder as tag for row for more efficient access.
                row.setTag(holder);

                // Initialise the MapView
                holder.initializeMapView();

                // Keep track of MapView
                mMaps.add(holder.mapView);
            } else {
                // View has already been initialised, get its holder
                holder = (ViewHolder) row.getTag();
            }

            // Get the NamedLocation for this item and attach it to the MapView
            NamedLocation item = getItem(position);
            holder.mapView.setTag(item);

            // Ensure the map has been initialised by the on map ready callback in ViewHolder.
            // If it is not ready yet, it will be initialised with the NamedLocation set as its tag
            // when the callback is received.
            if (holder.map != null) {
                // The map is already ready to be used
                setMapLocation(holder.map, item);
            }

            // Set the text label for this item
            holder.title.setText(item.name);

            return row;
        }

        /**
         * Retuns the set of all initialised {@link MapView} objects.
         *
         * @return All MapViews that have been initialised programmatically by this adapter
         */
        public HashSet<MapView> getMaps() {
            return mMaps;
        }
    }

    /**
     * Displays a {@link LiteListDemoActivity.NamedLocation} on a
     * {@link com.google.android.gms.maps.GoogleMap}.
     * Adds a marker and centers the camera on the NamedLocation with the normal map type.
     */
    private static void setMapLocation(GoogleMap map, NamedLocation data) {
        // Add a marker for this item and set the camera
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(data.location, 13f));
        map.addMarker(new MarkerOptions().position(data.location));

        // Set the map type back to normal.
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

    /**
     * Holder for Views used in the {@link LiteListDemoActivity.MapAdapter}.
     * Once the  the <code>map</code> field is set, otherwise it is null.
     * When the {@link #onMapReady(com.google.android.gms.maps.GoogleMap)} callback is received and
     * the {@link com.google.android.gms.maps.GoogleMap} is ready, it stored in the {@link #map}
     * field. The map is then initialised with the NamedLocation that is stored as the tag of the
     * MapView. This ensures that the map is initialised with the latest data that it should
     * display.
     */
    class ViewHolder implements OnMapReadyCallback {

        MapView mapView;

        TextView title;

        GoogleMap map;

        @Override
        public void onMapReady(GoogleMap googleMap) {
            MapsInitializer.initialize(getApplicationContext());
            map = googleMap;
            NamedLocation data = (NamedLocation) mapView.getTag();
            if (data != null) {
                setMapLocation(map, data);
            }
        }

        /**
         * Initialises the MapView by calling its lifecycle methods.
         */
        public void initializeMapView() {
            if (mapView != null) {
                // Initialise the MapView
                mapView.onCreate(null);
                // Set the map ready callback to receive the GoogleMap object
                mapView.getMapAsync(this);
            }
        }

    }

    /**
     * RecycleListener that completely clears the {@link com.google.android.gms.maps.GoogleMap}
     * attached to a row in the ListView.
     * Sets the map type to {@link com.google.android.gms.maps.GoogleMap#MAP_TYPE_NONE} and clears
     * the map.
     */
    private AbsListView.RecyclerListener mRecycleListener = new AbsListView.RecyclerListener() {

        @Override
        public void onMovedToScrapHeap(View view) {
            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder != null && holder.map != null) {
                // Clear the map and free up resources by changing the map type to none
                holder.map.clear();
                holder.map.setMapType(GoogleMap.MAP_TYPE_NONE);
            }

        }
    };

    /**
     * Location represented by a position ({@link com.google.android.gms.maps.model.LatLng} and a
     * name ({@link java.lang.String}).
     */
    private static class NamedLocation {

        public final String name;

        public final LatLng location;

        NamedLocation(String name, LatLng location) {
            this.name = name;
            this.location = location;
        }
    }
}

完整代码位于:https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/LiteListDemoActivity.java

答案 4 :(得分:-1)

我今天遇到了同样的问题 - 原来你必须在 MapActivity 中创建MapView,否则你会收到像无法浏览com.google.maps这样的错误。 MapView 左右......将MapView传递给ListAdapter并在需要时将其吐出。我不得不将MapView放在 RelativeLayout 中以根据需要调整高度和宽度(由于某种原因,MapView不会表现出“normal” viewish方式)。 如果您愿意,可以向我询问详细信息:)