【问题标题】:Android - MapView contained within a ListviewAndroid - Listview 中包含的 MapView
【发布时间】:2010-06-02 20:15:42
【问题描述】:

目前我正在尝试在 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 

提前感谢您的帮助!!

【问题讨论】:

  • 好吧,我咬一口。为什么 ListView 中需要 MapView?
  • 另外,您遇到了什么问题?
  • 假设 -- 您列出了特定业务的所有内容..我想显示它在列表中的位置的地图。我遇到的问题是我不知道从哪里开始。我想将它包含在 ListView 中,而不必启动一个全新的 Intent (这违背了 listview 的目的)。
  • 嘿 Ryan,你在 listAdapter 中显示 mapview 完成了吗?我也在尝试实现这样的功能。

标签: android listview android-mapview


【解决方案1】:

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

注意:这对于只需要在“地图”中显示位置但不需要在ListView 中与其交互的人可能很有用。点击ListView中的项目后,实际地图可以显示在详细信息页面上

正如@CaseyB 已经指出的那样,MapView 是一种沉重的观点。为了解决这方面的问题(并使我的生活变得更轻松;-)),我选择使用我的应用程序所需的几个参数来构建一个 URL,就像您为静态 Google 地图所做的那样。您可以在这里获得更多选择:https://developers.google.com/maps/documentation/staticmaps/

首先,当我为 ListView 构建数据时,我将 latitudelongitude 等数据传递给一个字符串,其中的一些静态变量取自上面提到的链接。我从 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(实际上是地图的图像)。

最终结果的示例。

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

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

【讨论】:

  • 哇,绝妙的答案!
  • 想不出更好的方法。干得好。
  • 我正在处理同样的问题。我想在列表视图中显示地图中两个位置之间的实际路线路径(不是直线)。有谁知道如何做到这一点?
  • 这仍然是最好的方法吗? Android Google Maps SDK 最近增加了“Lite Mode”,但这种方式似乎更轻量级。有没有办法可以为标记添加更长的标签?看来现在限制为 1 个字符。
  • @JohnOleynik:老实说,到目前为止,我还没有觉得需要更改静态地图的使用。话虽如此,我确实阅读了 SDK 的新 v2 中的 Lite Mode,它也是一个位置的位图。它是交互式的。这似乎有一个Lite Mode used in a ListView 的工作示例。我没有测试过它,甚至没有看过它的代码。但看起来很有希望。试一试。 :-)
【解决方案2】:

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

“每个进程仅支持一个 MapActivity。同时运行的多个 MapActivity 可能会以意想不到的方式干扰。”

(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 使用限制而出现问题。我不确定具体会怎样。

【讨论】:

  • 嘿史蒂夫——我不想显示多个地图视图..只有一个。此外,目标是让用户与地图进行交互,因此静态地图将无法正常工作。不过谢谢你的建议:)
  • 啊,我明白了。在这种情况下,您可以使用自定义列表适配器,如 CaseyB 指出的那样,或者如果列表中的项目在很大程度上是异构的,则可能只使用 ScrollView 中的垂直 LinearLayout。
【解决方案3】:

在这种情况下,您可以像添加任何其他视图一样将 MapView 添加到列表中。 Here's a quick tutorial 关于如何创建自定义列表适配器。但我必须提醒你,MapView 是一个非常重的视图,如果你试图在屏幕上显示一堆,你会发现应用程序很慢!您可以在列表项中添加一个按钮,将用户带到另一个页面,其中包含更多信息,包括地图。

【讨论】:

  • 我认为,该链接不适用于在自定义适配器中显示地图视图...请指导我在 listadapter 中拥有地图
  • 我有 SupportMapFragment ,我可以在 listview 行内使用吗?我有自定义适配器,但我不知道如何在 getChildView()BaseExpandableListAdapter 中使用地图。简单地说,我们可以像((TextView) convertView.findViewById(R.id.parent_txt_list_title)).setText(parent.getTitle()); 那样做,但是我们如何为地图做同样的事情。你能帮我吗
  • 我在列表视图中添加了一张地图,但面临缩放/捏合问题。因为父级滚动。
【解决方案4】:

有可能,来自 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

【解决方案5】:

我今天遇到了同样的问题 - 原来您必须在 MapActivity 中创建 MapView,否则您会收到类似 Unable to Inflate View com.google.maps 的错误。 MapView 左右...比将此 MapView 传递给您的 ListAdapter 并在需要时将其吐出。我必须将 MapView 放置在 RelativeLayout 中以根据需要调整高度和宽度(出于某种原因,MapView 的行为不符合 “正常” 视图方式)。 如果你愿意,可以向我询问详细信息:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多