最近做了一个百度地图离线地图的功能,虽然功能实现了,但过程中也碰到了一些问题。首先,看看效果图吧。

1、离线地图相关API

API地址:http://wiki.lbsyun.baidu.com/cms/androidsdk/doc/v4_0_0/index.html

MKOfflineMap类

主要的一个类,提供了离线地图的管理功能,例如,下载,暂停、更新,删除等功能。每次只允许一个下载任务进行,后面的需要排队。

  • void destroy()
    销毁离线地图管理模块,不用时调用
  • java.util.ArrayList< MKOLUpdateElement> getAllUpdateInfo()
    返回各城市离线地图更新信息,已下载的离线地图
  • java.util.ArrayList< MKOLSearchRecord> getHotCityList()
    返回热门城市列表
  • java.util.ArrayList getOfflineCityList()
    返回支持离线地图城市列表
  • MKOLUpdateElement getUpdateInfo(int cityID)
    返回指定城市ID离线地图更新信息
  • boolean init(MKOfflineMapListener listener)
    初使化
  • boolean pause(int cityID)
    暂停下载或更新指定城市ID的离线地图
  • boolean remove(int cityID)
    删除指定城市ID的离线地图
  • java.util.ArrayList< MKOLSearchRecord> searchCity(java.lang.String
    cityName)
    根据城市名搜索该城市离线地图记录
  • boolean start(int cityID)
    启动下载指定城市ID的离线地图,或在暂停更新某城市后继续更新下载某城市离线地图
  • boolean update(int cityID)
    启动更新指定城市ID的离线地图

MKOLSearchRecord类

离线地图搜索城市记录结构

  • java.util.ArrayList< MKOLSearchRecord> childCities
    子城市列表
  • int cityID
    城市ID
  • java.lang.String cityName
    城市名称
  • int cityType
    城市类型0:全国;1:省份;2:城市,如果是省份,可以通过childCities得到子城市列表
  • int size
    数据包总大小

MKOLUpdateElement类

离线地图更新信息,下面是其中的一些字段

  • int cityID
    城市ID
  • java.lang.String cityName
    城市名称
  • static int DOWNLOADING
    正在下载
  • LatLng geoPt
    城市中心点坐标
  • int level
    离线包地图层级
  • int ratio
    下载比率,100为下载完成
  • int serversize
    服务端数据大小
  • int size
    已下载数据大小
  • int status
    下载状态
  • boolean update
    是否为更新

MKOfflineMapListener接口

该接口返回新安装离线地图、下载更新、数据版本更新等结果,用户需要实现该接口以处理相应事件。里面有一个唯一的方法:

  • void onGetOfflineMapState(int type, int state) 返回通知事件

2、主要代码

OfflineActivity类

/* 此Demo用来演示离线地图的下载和显示 */
public class OfflineActivity extends Activity implements MKOfflineMapListener {private MKOfflineMap mOffline = null;private TextView cidView;private TextView stateView;private EditText cityNameView;private HashMap<String, Boolean> hashMap = new HashMap<String, Boolean>(); //是否已下载;private CityExpandableListAdapter adapter;private HotcityListAdapter hAdapter;private OfflineHandler offlineHandler;private MKOLSearchRecord currentRecord;private ArrayList<MKOLUpdateElement> loadingList = new ArrayList<MKOLUpdateElement>();private ArrayList<MKOLUpdateElement> loadedList = new ArrayList<MKOLUpdateElement>();public HashMap<String,String> clickMap;/*** 已下载的离线地图信息列表*/public ArrayList<MKOLUpdateElement> localMapList = null;private LocalMapAdapter lAdapter = null;private loadingMapAdapter dAdapter = null;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_offline);ImageButton back = (ImageButton) findViewById(R.id.back);back.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {OfflineActivity.this.finish();}});offlineHandler = new OfflineHandler(this);mOffline = new MKOfflineMap();mOffline.init(this);initView();initCurLocation();}LocationManager lm = null; // location管理器LocationClient mLocClient;private void initCurLocation(){lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);if (lm != null) {// 定位初始化mLocClient = new LocationClient(this);mLocClient.registerLocationListener(new MyLocationListenner());LocationClientOption option = new LocationClientOption();option.setOpenGps(true);// 打开gpsoption.setCoorType("bd09ll"); // 设置坐标类型option.setPriority(LocationClientOption.NetWorkFirst);//设置网络优先(不设置,默认是gps优先)option.setAddrType("all");// 返回的定位结果包含地址信息option.setScanSpan(10000);// 设置发起定位请求的间隔时间为10s(小于1秒则一次定位)mLocClient.setLocOption(option);mLocClient.start();}else {SystemUtil.showMessage("请打开GPS定位设置");}}public void setCurrentLocation(String currentLocation) {TextView current = (TextView) findViewById(R.id.current_name);current.setText(currentLocation);currentRecord = search(currentLocation);RelativeLayout currentItem = (RelativeLayout)findViewById(R.id.current_item);currentItem.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if (hashMap.get(currentRecord.cityName)){Toast.makeText(OfflineActivity.this, "离线地图已下载", Toast.LENGTH_LONG).show();}else {TextView currentSize = (TextView) v.findViewById(R.id.current_size);currentSize.setText("正在下载");start(currentRecord.cityID);}}});}public class MyLocationListenner implements BDLocationListener {@Overridepublic void onReceiveLocation(BDLocation location) {MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())// 此处设置开发者获取到的方向信息,顺时针0-360.direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).build();String address=location.getAddrStr();String city=location.getCity();//            System.out.println("地址:"+address+"城市:"+city);setCurrentLocation(city);}public void onReceivePoi(BDLocation poiLocation) {}}private void initView() {// 获取已下过的离线地图信息localMapList = mOffline.getAllUpdateInfo();if (localMapList == null) {localMapList = new ArrayList<MKOLUpdateElement>();}ListView localMapListView = (ListView) findViewById(R.id.localmaplist);lAdapter = new LocalMapAdapter();localMapListView.setAdapter(lAdapter);ListView loadingListView = (ListView)findViewById(R.id.lodinglist);dAdapter = new loadingMapAdapter();loadingListView.setAdapter(dAdapter);//        cidView = (TextView) findViewById(R.id.cityid);
//        cityNameView = (EditText) findViewById(R.id.city);
//        stateView = (TextView) findViewById(R.id.state);ListView hotCityList = (ListView) findViewById(R.id.hotcitylist);final ArrayList<Integer> hotCities = new ArrayList<Integer>();// 获取热门城市列表final ArrayList<MKOLSearchRecord> records1 = mOffline.getHotCityList();if (records1 != null) {for (MKOLSearchRecord r : records1) {hotCities.add(r.cityID);}}hAdapter = new HotcityListAdapter(this, records1,hashMap);hotCityList.setAdapter(hAdapter);hotCityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {if (hashMap.get(records1.get(position).cityName)){Toast.makeText(OfflineActivity.this, "离线地图已下载", Toast.LENGTH_LONG).show();}else {TextView childSize = (TextView) view.findViewById(R.id.child_size);childSize.setText("正在下载");start(records1.get(position).cityID);}}});ExpandableListView allCityList = (ExpandableListView) findViewById(R.id.allcitylist);// 获取所有支持离线地图的城市final ArrayList<MKOLSearchRecord> records2 = mOffline.getOfflineCityList();clickMap = new HashMap<String, String>();if (records1 != null) {for (MKOLSearchRecord r : records2) {
//                allCities.add(r.cityName+"--" + this.formatDataSize(r.size));
//                allCitiyIds.add(r.cityID);hashMap.put(r.cityName,downList(r.cityName));clickMap.put(r.cityName, "0");if (r.childCities != null && r.childCities.size() != 0){ArrayList<MKOLSearchRecord> childrecord = r.childCities;
//for (MKOLSearchRecord cr : childrecord){hashMap.put(cr.cityName,downList(cr.cityName));}}}}adapter = new CityExpandableListAdapter(this,records2,hashMap);allCityList.setAdapter(adapter);allCityList.setGroupIndicator(null);hAdapter.notifyDataSetChanged();allCityList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {@Overridepublic boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {if (records2 != null ){MKOLSearchRecord record = records2.get(groupPosition);if (record.childCities == null){if (hashMap.get(record.cityName)){Toast.makeText(OfflineActivity.this, "离线地图已下载", Toast.LENGTH_LONG).show();}else{
//                            System.out.println("simplename:"+v.getClass().getSimpleName());int cd = record.cityID;start(cd);/* int size = ((ViewGroup)v).getChildCount();for (int i = 0 ; i< size; i++){View child = ((ViewGroup)v).getChildAt(i);System.out.println("simplename:"+child.getClass().getSimpleName());}View child = ((ViewGroup)v).getChildAt(1);((TextView)child).setText("正在下载");*/clickMap.put(record.cityName, "1");
//                            adapter.notifyDataSetChanged();}}}return false;}});allCityList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {@Overridepublic boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {if (records2 != null){MKOLSearchRecord record = records2.get(groupPosition);MKOLSearchRecord cldred = record.childCities.get(childPosition);if (hashMap.get(cldred.cityName)){Toast.makeText(OfflineActivity.this, "离线地图已下载", Toast.LENGTH_LONG).show();}else {TextView childSize = (TextView) v.findViewById(R.id.child_size);childSize.setText("正在下载");start(cldred.cityID);}}return false;}});LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);lm.setVisibility(View.GONE);cl.setVisibility(View.VISIBLE);}public boolean downList(String cityName){Boolean flag = false;if (localMapList != null){for (int i = 0; i <localMapList.size(); i++){MKOLUpdateElement element= localMapList.get(i);
//                System.out.println("离线城市:"+element.cityName);if (cityName.equals(element.cityName)){flag = true;break;}else {flag =  false;}}}return flag;}/*** 切换至城市列表** @param view*/public void clickCityListButton(View view) {LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);lm.setVisibility(View.GONE);cl.setVisibility(View.VISIBLE);Button clButton = (Button)findViewById(R.id.clButton);clButton.setBackgroundResource(R.drawable.city_list_pressed);clButton.setTextColor(Color.parseColor("#4196fd"));Button localButton = (Button) findViewById(R.id.localButton);localButton.setBackgroundResource(R.drawable.down_manager);localButton.setTextColor(Color.parseColor("#ffffff"));}/*** 切换至下载管理列表** @param view*/public void clickLocalMapListButton(View view) {LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);lm.setVisibility(View.VISIBLE);cl.setVisibility(View.GONE);Button localButton = (Button) findViewById(R.id.localButton);localButton.setBackgroundResource(R.drawable.down_manager_pressed);localButton.setTextColor(Color.parseColor("#4196fd"));Button clButton = (Button)findViewById(R.id.clButton);clButton.setBackgroundResource(R.drawable.city_list);clButton.setTextColor(Color.parseColor("#ffffff"));updateView(null, false);}/*** 搜索离线需市** @param*/public MKOLSearchRecord search(String city) {ArrayList<MKOLSearchRecord> records = mOffline.searchCity(city);if (records == null || records.size() != 1) {return null;}
//        cidView.setText(String.valueOf(records.get(0).cityID));TextView current_size = (TextView) findViewById(R.id.current_size);if (hashMap.get(records.get(0).cityName)){current_size.setText("已下载");}else {current_size.setText(formatDataSize(records.get(0).size));}return records.get(0);}/*** 开始下载** @param*/public void start(int cityid) {
//        int cityid = Integer.parseInt(cidView.getText().toString());mOffline.start(cityid);clickLocalMapListButton(null);
//        Toast.makeText(this, "开始下载离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();updateView(null, false);}/*** 暂停下载** @param view*/public void stop(View view) {int cityid = Integer.parseInt(cidView.getText().toString());mOffline.pause(cityid);Toast.makeText(this, "暂停下载离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();updateView(null, false);}/*** 删除离线地图** @param view*/public void remove(View view) {int cityid = Integer.parseInt(cidView.getText().toString());mOffline.remove(cityid);Toast.makeText(this, "删除离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();updateView(null,false);}/*** 更新状态显示*/public void updateView(MKOLUpdateElement element, boolean flag) {localMapList = mOffline.getAllUpdateInfo();if (localMapList == null) {localMapList = new ArrayList<MKOLUpdateElement>();}loadingList.clear();loadedList.clear();for (MKOLUpdateElement element1 : localMapList){if (element1.ratio != 100){loadingList.add(element1);}else {loadedList.add(element1);}}if (element != null){hashMap.put(element.cityName, flag);if (currentRecord.cityID == element.cityID){TextView currentSize = (TextView) findViewById(R.id.current_size);if(flag){currentSize.setText("已下载");}else {currentSize.setText(formatDataSize(element.size));}}else {adapter.notifyDataSetChanged();hAdapter.notifyDataSetChanged();}}lAdapter.notifyDataSetChanged();dAdapter.notifyDataSetChanged();}@Overrideprotected void onPause() {
//        int cityid = Integer.parseInt(cidView.getText().toString());
//        MKOLUpdateElement temp = mOffline.getUpdateInfo(cityid);
//        if (temp != null && temp.status == MKOLUpdateElement.DOWNLOADING) {//            mOffline.pause(cityid);
//        }super.onPause();}@Overrideprotected void onResume() {super.onResume();}public String formatDataSize(int size) {String ret = "";if (size < (1024 * 1024)) {ret = String.format("%dK", size / 1024);} else {ret = String.format("%.1fM", size / (1024 * 1024.0));}return ret;}@Overrideprotected void onDestroy() {/*** 退出时,销毁离线地图模块*/mOffline.destroy();super.onDestroy();}@Overridepublic void onGetOfflineMapState(int type, int state) {switch (type) {case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {MKOLUpdateElement update = mOffline.getUpdateInfo(state);// 处理下载进度更新提示if (update != null) {//                    stateView.setText(String.format("%s : %d%%", update.cityName,
//                            update.ratio));
//                    System.out.println("ratio:"+update.ratio);if (update.ratio == 100){updateView(update,true);}else {updateView(null, false);}}}break;case MKOfflineMap.TYPE_NEW_OFFLINE:// 有新离线地图安装Log.d("OfflineDemo", String.format("add offlinemap num:%d", state));break;case MKOfflineMap.TYPE_VER_UPDATE:// 版本更新提示// MKOLUpdateElement e = mOffline.getUpdateInfo(state);break;default:break;}}/*** 正在下载城市列表适配器*/public class loadingMapAdapter extends BaseAdapter{@Overridepublic int getCount() {return loadingList.size();}@Overridepublic Object getItem(int position) {return loadingList.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView == null){convertView = LayoutInflater.from(OfflineActivity.this).inflate(R.layout.loding_list, null);}TextView name = (TextView) convertView.findViewById(R.id.city_name);TextView size = (TextView)convertView.findViewById(R.id.city_size);TextView ratio = (TextView)convertView.findViewById(R.id.down_ratio);ImageButton manager= (ImageButton) convertView.findViewById(R.id.down_manager);final MKOLUpdateElement ele = loadingList.get(position);name.setText(ele.cityName);size.setText(formatDataSize(ele.size));ratio.setText(ele.ratio+"%");manager.setOnClickListener(new OnClickListener() {boolean flag = true;@Overridepublic void onClick(View v) {if (flag) {mOffline.pause(ele.cityID);v.setBackgroundResource(R.drawable.loading_start);flag = false;}else {mOffline.start(ele.cityID);v.setBackgroundResource(R.drawable.loading_pause);flag = true;}}});return convertView;}}/*** 离线地图管理列表适配器*/public class LocalMapAdapter extends BaseAdapter {@Overridepublic int getCount() {return loadedList.size();}@Overridepublic Object getItem(int index) {return loadedList.get(index);}@Overridepublic long getItemId(int index) {return index;}@Overridepublic View getView(int index, View view, ViewGroup arg2) {MKOLUpdateElement e = (MKOLUpdateElement) getItem(index);view = View.inflate(OfflineActivity.this,R.layout.offline_localmap_list, null);initViewItem(view, e);return view;}void initViewItem(View view, final MKOLUpdateElement e) {Button remove = (Button) view.findViewById(R.id.remove);TextView title = (TextView) view.findViewById(R.id.title);TextView update = (TextView) view.findViewById(R.id.update);
//            TextView ratio = (TextView) view.findViewById(R.id.ratio);Button doUpdate = (Button) view.findViewById(R.id.exe_update);
//            ratio.setText(e.ratio + "%");title.setText(e.cityName);if (e.update) {update.setText("可更新");} else {update.setText("最新");}remove.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {mOffline.remove(e.cityID);clickMap.put(e.cityName,"0");updateView(e, false);}});doUpdate.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {mOffline.update(e.cityID);}});}}}

布局文件activity_offline.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="@color/white"><RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"android:background="@drawable/bg_titlebar"><ImageButtonandroid:id="@+id/back"android:layout_width="32dp"android:layout_height="32dp"android:layout_centerVertical="true"android:layout_marginLeft="10.0dip"android:paddingRight="8.0dip"android:background="@drawable/titlebar_back"android:contentDescription="@string/back" /><LinearLayoutandroid:id="@+id/city_list"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_centerInParent="true"android:padding="1dp"android:background="@drawable/edit_search2"><Buttonandroid:id="@+id/clButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="clickCityListButton"android:padding="8dp"android:text="城市列表"android:textColor="#4196fd"android:background="@drawable/city_list_pressed"/><Buttonandroid:id="@+id/localButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="clickLocalMapListButton"android:padding="8dp"android:text="下载管理"android:textColor="@color/white"android:background="@drawable/down_manager"/></LinearLayout></RelativeLayout>
<!--    <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="50dip"android:orientation="horizontal" ><TextViewandroid:id="@+id/cityid"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="131" />&lt;!&ndash; 隐藏输入法用 &ndash;&gt;<LinearLayoutandroid:layout_width="0px"android:layout_height="0px"android:focusable="true"android:focusableInTouchMode="true" /><EditTextandroid:id="@+id/city"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="北京" /><Buttonandroid:id="@+id/search"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="search"android:text="搜索" /></LinearLayout><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="50dip"android:orientation="horizontal" ><TextViewandroid:id="@+id/state"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="已下载:-" /><Buttonandroid:id="@+id/start"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="start"android:text="开始" /><Buttonandroid:id="@+id/stop"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="stop"android:text="停止" /><Buttonandroid:id="@+id/del"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="remove"android:text="删除" /></LinearLayout>--><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/citylist_layout"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextViewandroid:layout_width="match_parent"android:layout_height="32dp"android:text="当前位置"android:layout_marginLeft="2dp"android:textSize="16sp"android:gravity="center_vertical"android:textColor="@color/font_color"android:background="#f0f3f5"/><RelativeLayout android:layout_width="match_parent" android:layout_height="40dp"android:id="@+id/current_item"><TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true"android:text="定位中..." android:textColor="@color/font_color" android:textSize="16sp"android:id="@+id/current_name" android:layout_marginLeft="12dp"/><TextView android:layout_width="wrap_content" android:layout_height="wrap_content"android:text="--" android:textColor="@color/font_color" android:id="@+id/current_size"android:layout_centerVertical="true" android:layout_alignParentRight="true" android:layout_marginRight="12dp"/></RelativeLayout><TextViewandroid:layout_width="match_parent"android:layout_height="32dp"android:text="热门城市"android:layout_marginLeft="2dp"android:textSize="16sp"android:gravity="center_vertical"android:textColor="@color/font_color"android:background="#f0f3f5"/><ListViewandroid:id="@+id/hotcitylist"android:layout_width="fill_parent"android:layout_height="200dip"android:cacheColorHint="#00000000"android:scrollingCache="false"android:listSelector="@drawable/item_selector"android:divider="#cccccc"android:dividerHeight="0.5dp"/><TextViewandroid:layout_width="fill_parent"android:layout_height="32dp"android:layout_marginLeft="2dp"android:text="全国"android:textSize="16sp"android:gravity="center_vertical"android:textColor="@color/font_color"android:background="#f0f3f5"/><ExpandableListViewandroid:id="@+id/allcitylist"android:layout_width="fill_parent"android:cacheColorHint="#00000000"android:scrollingCache="false"android:alwaysDrawnWithCache="false"android:layout_height="fill_parent"android:scrollbars="none"android:divider="#cccccc"android:listSelector="@drawable/item_selector"android:dividerHeight="0.5dp"android:childDivider="@drawable/item_divider"/></LinearLayout><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/localmap_layout"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextView android:layout_width="match_parent"android:layout_height="32dp"android:text="正在下载中"android:layout_marginLeft="2dp"android:textSize="16sp"android:gravity="center_vertical"android:textColor="@color/font_color"android:background="#f0f3f5"/><ListView android:layout_width="match_parent" android:layout_height="wrap_content"android:id="@+id/lodinglist"  android:cacheColorHint="#00000000"android:scrollingCache="false" android:divider="#cccccc"android:dividerHeight="0.5dp"></ListView><View android:layout_width="match_parent" android:layout_height="40dp" android:background="#fff"></View><TextViewandroid:layout_width="fill_parent"android:layout_height="32dp"android:text="已下载城市 "android:layout_marginLeft="2dp"android:textSize="16sp"android:gravity="center_vertical"android:textColor="@color/font_color"android:background="#f0f3f5"/><ListViewandroid:id="@+id/localmaplist"android:layout_width="fill_parent"android:layout_height="wrap_content"android:cacheColorHint="#00000000"android:scrollingCache="false"android:divider="#cccccc"android:dividerHeight="0.5dp"/></LinearLayout></LinearLayout>

CityExpandableListAdapter类

public class CityExpandableListAdapter extends BaseExpandableListAdapter {private OfflineActivity context;private ArrayList<MKOLSearchRecord> records;private HashMap<String, Boolean> hashMap;public CityExpandableListAdapter(OfflineActivity context, ArrayList<MKOLSearchRecord> records, HashMap<String, Boolean> hashMap){this.context = context;this.records = records;this.hashMap = hashMap;System.out.println("hashMapsize:"+hashMap.size());}@Overridepublic int getGroupCount() {return records.size();}@Overridepublic int getChildrenCount(int groupPosition) {if (records.get(groupPosition).childCities != null){return records.get(groupPosition).childCities.size();}return 0;}@Overridepublic Object getGroup(int groupPosition) {return records.get(groupPosition);}@Overridepublic Object getChild(int groupPosition, int childPosition) {if (records.get(groupPosition).childCities != null){return records.get(groupPosition).childCities.get(childPosition);}return null;}@Overridepublic long getGroupId(int groupPosition) {return groupPosition;}@Overridepublic long getChildId(int groupPosition, int childPosition) {return childPosition;}@Overridepublic boolean hasStableIds() {return true;}@Overridepublic View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {GroupHolder groupHolder = null;if (convertView == null){convertView = LayoutInflater.from(context).inflate(R.layout.expandlist_group, parent, false);groupHolder = new GroupHolder();groupHolder.txt = (TextView)convertView.findViewById(R.id.names);groupHolder.size = (TextView)convertView.findViewById(R.id.map_size);groupHolder.img = (ImageView)convertView.findViewById(R.id.indicator_arrow);convertView.setTag(groupHolder);}else{groupHolder = (GroupHolder)convertView.getTag();}String cityName = records.get(groupPosition).cityName;groupHolder.txt.setText(cityName);if (records.get(groupPosition).childCities == null){groupHolder.img.setVisibility(View.GONE);groupHolder.size.setVisibility(View.VISIBLE);if (hashMap.get(cityName)){groupHolder.size.setText("已下载");}else {if ("1".equals(context.clickMap.get(cityName))){groupHolder.size.setText("正在下载");}else {groupHolder.size.setText(context.formatDataSize(records.get(groupPosition).size));}}}else {groupHolder.size.setVisibility(View.GONE);groupHolder.img.setVisibility(View.VISIBLE);}//判断isExpanded就可以控制是按下还是关闭,同时更换图片if(isExpanded){groupHolder.img.setBackgroundResource(R.drawable.moreitems_arrow);}else{groupHolder.img.setBackgroundResource(R.drawable.moreitems_arrow_down); }return convertView;}@Overridepublic View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {ItemHolder itemHolder = null;if (convertView == null){
//            convertView = convertView.inflate(context, R.layout.expandlist_item, null);convertView = LayoutInflater.from(context).inflate(R.layout.expandlist_item, parent,false);itemHolder = new ItemHolder();itemHolder.txt = (TextView)convertView.findViewById(R.id.child_names);itemHolder.size  = (TextView)convertView.findViewById(R.id.child_size);
//            itemHolder.img = (ImageView)convertView.findViewById(R.id.img);convertView.setTag(itemHolder);}else{itemHolder = (ItemHolder)convertView.getTag();}if (records.get(groupPosition).childCities != null){ArrayList<MKOLSearchRecord> list = records.get(groupPosition).childCities;if (list.size()>0){MKOLSearchRecord info = list.get(childPosition);String cityName  = info.cityName;itemHolder.txt.setText(cityName);if (hashMap.get(cityName)){itemHolder.size.setText("已下载");}else {itemHolder.size.setText(context.formatDataSize(info.size));}}}return convertView;}@Overridepublic boolean isChildSelectable(int groupPosition, int childPosition) {return true;}class GroupHolder{public TextView txt;public TextView size;public ImageView img;}class ItemHolder{public ImageView img;public TextView size;public TextView txt;}}

3、遇到的问题

  • 关于ExpandableListview

在setOnGroupClickListener中修改group上TextView的文字时无效;
View child = ((ViewGroup)v).getChildAt(1);
((TextView)child).setText(“正在下载”)
这样设置没有效果,但是在setOnChildClickListener上做类似的修改是有效的,这里在点击group时,好像setOnGroupClickListener去调用了adapter的notifyDataSetChanged(),但是在程序中没找到,难道这是默认行为?
最后还是通过下面的方法解决
clickMap.put(record.cityName, “1”);
adapter.notifyDataSetChanged();
通过修改数据,然后调用adapter.notifyDataSetChanged();在adapter中进行修改;

在item根部局上设置minHeight属性可以有效的设置item的高度。

  • LayoutInflater类的infalter方法,几种重载方法的区别:

之前对这个有所了解,这里碰到的时候又忘记了,再次记录下。
1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。
具体这篇文件解释很清楚:http://blog.csdn.net/guolin_blog/article/details/12921889

android 百度地图离线地图功能相关推荐

  1. Android 百度地图 SDK v3.0.0 (四) 引入离线地图功能

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37758097 一直觉得地图应用支持离线地图很重要啊,我等移动2G屌丝,流量不易, ...

  2. Android百度地图(四)如何引入离线地图包

    Android百度地图(四)如何引入离线地图包 本文代码在http://blog.csdn.net/xyzz609/article/details/51955363的基础上进一步修改,有兴趣的同学可以 ...

  3. android地图入门,android 百度地图入门01 (史上最详没有之一)

    最近一直和百度地图打交道,写几篇博客记录一下吧,目前最新版是4.0的 ,之前我用的是3.7的, 就以4.0的为例说一下最基本的配置流程吧. 一.准备工作 1.申请一个百度地图开发者账户--地址:htt ...

  4. Android百度地图

    Android百度地图 1.先激活百度地图的账户 2.在终端获取SHA,创建应用 3.在百度地图开发平台获取AK 4.在官网下载所需配置 5.解压后放在项目的libs文件下 6.设计如下界面: 7.在 ...

  5. Android百度地图之位置定位和附近查找代码简单实现 (上)

    很长时间没有做Android相关知识了,闲暇之余再弄了弄最新的百度地图API,主要是进行百度地图附近餐馆查找功能来练练手,同时熟悉下最新的API教程.文章比较基础,也希望对你有所帮助~参考前文:   ...

  6. Android studio百度地图SDK开发 2020最新超详细的Android 百度地图开发讲解(3) 路线规划步行骑行驾车路线规划

    2020最新超详细的Android 百度地图开发讲解(3) 路线规划步行骑行驾车路线规划 开发前配置,显示基本地图,实时定位等查看之前代码,此博客紧接上一博客:https://blog.csdn.ne ...

  7. Android百度地图开发入门教程

    Android百度地图开发入门教程 1.平台注册登录 2.创建应用 3.Android studio配置 4.代码编写 5.最终效果(建议真机) 1.平台注册登录 登录百度地图开放平台网站注册并登录 ...

  8. 百度地图离线开发demo(vue+百度地图3.0+百度瓦片)(仅供参考,学习探讨)

    公司需求开发离线地图功能.搜索学习,踩坑,试验(由于参考借鉴了n多文章,就不分别贴出对应文章了,感谢分享...),最终整合了一套集成vue的离线地图开发方案,文章将分享一整套的解决方案思路与方式.后续 ...

  9. Android百度地图(一):百度地图定位sdk 类方法参数、定位原理详细介绍

    ***转载.引用请标明出处*** http://www.jianshu.com/p/29ccac3e1e42 本文出自[zhh_happig的简书博客](http://www.jianshu.com/ ...

  10. Android - 百度地图打包之后出现的问题

    一.关于百度地图开发-调试通过-打包失败(授权Key不正确) 百度地图开发调试的应用程序正常,打包后显示授权key失败 这是由于调试生成的应用程序使用的是eclipse默认的SHA1的值 我们需要使用 ...

最新文章

  1. 同花顺python_python的解析库pyquery解析并读取同花顺网站的焦点新闻
  2. Linux的/etc/init.d:用service命令可执行init.d目录中相应服务的脚本
  3. 多租户的数据库方案分析
  4. 【JavaScript】js数组与字符串的相互转换
  5. .NET Core 中使用 Humanizer 显示友好时间格式
  6. java项目_好程序员Java分享从入门到服务端项目开发的过程
  7. java登陆session用法_Java web 登录 使用shiro和基于session的方式有何不同?
  8. Kotlin协程的迷惑
  9. 【转载】学习Android界面设计的超级利器HierarchyView.bat
  10. 蓝桥杯 BASIC-14 基础练习 时间转换
  11. pppoe路由桥混合模式_192.168.1.1路由器怎么设置和登陆
  12. 台式计算机的显卡,台式电脑显卡天梯图-台式机显卡性能排名
  13. 数字媒体技术 计算机类 专业大学排名,2019年全国数字媒体技术专业大学排名(20强)...
  14. 【AE教程】AI文件导入AE方法
  15. 中医药大学远程教育计算机,《中医药大学远程教育计算机作业 1-7》.doc
  16. Window设置开机自启软件的几种方式
  17. wifi 小程序 透传_微信小程序实现的一键连接wifi功能示例
  18. 海龟交易法则(中译文)
  19. linux下安装包打包依赖库所走的弯路
  20. Python使用Reportlab处理PDF数据 - 图形和图表

热门文章

  1. python贴吧系统_【新手】python爬虫遍历贴吧用户
  2. Hibernate 学习的书-夏昕(2)
  3. 1.7亿,国家重点研发计划“综合交通运输与智能交通”2019年项目申报开始
  4. 某网站字幕加密的wasm分析
  5. 宿舍管理系统简单的增删改查
  6. origin拟合曲线
  7. linux下文本去重
  8. 十代主板改win7_微星b460主板装win7系统及bios设置教程(支持十代usb驱动)
  9. 方差分析与正交试验设计(四)
  10. OpenCV 模板匹配(Template Match)