android 百度地图离线地图功能

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

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() {
            @Override
            public 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);// 打开gps
            option.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() {
            @Override
            public 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 {

        @Override
        public 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() {
            @Override
            public 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() {
            @Override
            public 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() {
            @Override
            public 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();
    }

    @Override
    protected 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();
    }

    @Override
    protected 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;
    }

    @Override
    protected void onDestroy() {
        /**
         * 退出时,销毁离线地图模块
         */
        mOffline.destroy();
        super.onDestroy();
    }

    @Override
    public 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{

        @Override
        public int getCount() {
            return loadingList.size();
        }

        @Override
        public Object getItem(int position) {
            return loadingList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public 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;
                @Override
                public 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 {

        @Override
        public int getCount() {
            return loadedList.size();
        }

        @Override
        public Object getItem(int index) {
            return loadedList.get(index);
        }

        @Override
        public long getItemId(int index) {
            return index;
        }

        @Override
        public 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() {
                @Override
                public void onClick(View arg0) {
                    mOffline.remove(e.cityID);
                    clickMap.put(e.cityName,"0");
                    updateView(e, false);
                }
            });
            doUpdate.setOnClickListener(new OnClickListener() {
                @Override
                public 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">
        <ImageButton
                android: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" />
        <LinearLayout
                android: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">

            <Button
                    android: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"/>

            <Button
                    android: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>
<!--    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/cityid"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="131" />
        &lt;!&ndash; 隐藏输入法用 &ndash;&gt;

        <LinearLayout
            android:layout_width="0px"
            android:layout_height="0px"
            android:focusable="true"
            android:focusableInTouchMode="true" />

        <EditText
            android:id="@+id/city"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="北京" />

        <Button
            android:id="@+id/search"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="search"
            android:text="搜索" />
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/state"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="已下载:-" />

        <Button
            android:id="@+id/start"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="start"
            android:text="开始" />

        <Button
            android:id="@+id/stop"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="stop"
            android:text="停止" />

        <Button
            android:id="@+id/del"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="remove"
            android:text="删除" />
    </LinearLayout>-->



    <LinearLayout
        xmlns: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" >
        <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"/>
        <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>
        <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: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"/>

        <TextView
            android: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"/>

        <ExpandableListView
                android: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>

    <LinearLayout
        xmlns: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>
        <TextView
            android: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"/>

        <ListView
            android: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());
    }

    @Override
    public int getGroupCount() {
        return records.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (records.get(groupPosition).childCities != null)
        {
            return records.get(groupPosition).childCities.size();
        }
        return 0;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return records.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        if (records.get(groupPosition).childCities != null)
        {
            return records.get(groupPosition).childCities.get(childPosition);
        }
        return null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public 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;
    }

    @Override
    public 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;
    }

    @Override
    public 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

评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值