android 百度地圖離線地圖功能

最近作了一個百度地圖離線地圖的功能,雖然功能實現了,但過程當中也碰到了一些問題。首先,看看效果圖吧。
這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述html

一、離線地圖相關API

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

MKOfflineMap類android

主要的一個類,提供了離線地圖的管理功能,例如,下載,暫停、更新,刪除等功能。每次只容許一個下載任務進行,後面的須要排隊。git

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類app

離線地圖搜索城市記錄結構ide

java.util.ArrayList< MKOLSearchRecord> childCities
子城市列表 int cityID
城市ID java.lang.String cityName
城市名稱 int cityType
城市類型0:全國;1:省份;2:城市,若是是省份,能夠經過childCities獲得子城市列表 int size
數據包總大小佈局

MKOLUpdateElement類ui

離線地圖更新信息,下面是其中的一些字段this

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) 返回通知事件

二、主要代碼

OfflineActivity類

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

<code class="hljs java">/* 此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(); button="" cl="(LinearLayout)" clbutton="(Button)findViewById(R.id.clButton);" element="localMapList.get(i);" else="" flag="true;" if="" linearlayout="" lm="(LinearLayout)" localbutton="(Button)" mkolsearchrecord="" mkolupdateelement="" param="" public="" return="" string="" view="" void=""> 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);

                }

            });

        }

 

    }

 

}</mkolupdateelement></localmaplist.size();></mkolsearchrecord></string,></mkolsearchrecord></mkolsearchrecord></integer></integer></mkolupdateelement></mkolupdateelement></string,string></mkolupdateelement></mkolupdateelement></mkolupdateelement></mkolupdateelement></string,></string,></code>

佈局文件activity_offline.xml

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

<code class="hljs java"><code class="hljs applescript"><!--?xml version="1.0" encoding="utf-8"?-->

<linearlayout android:background="@color/white" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">

    <relativelayout android:background="@drawable/bg_titlebar" android:layout_height="wrap_content" android:layout_width="match_parent">

        <imagebutton android:background="@drawable/titlebar_back" android:contentdescription="@string/back" android:id="@+id/back" android:layout_centervertical="true" android:layout_height="32dp" android:layout_marginleft="10.0dip" android:layout_width="32dp" android:paddingright="8.0dip">

        <linearlayout android:background="@drawable/edit_search2" android:id="@+id/city_list" android:layout_centerinparent="true" android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="horizontal" android:padding="1dp"><button android:background="@drawable/city_list_pressed" android:id="@+id/clButton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="clickCityListButton" android:padding="8dp" android:text="城市列表" android:textcolor="#4196fd"></button><button android:background="@drawable/down_manager" android:id="@+id/localButton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="clickLocalMapListButton" android:padding="8dp" android:text="下載管理" android:textcolor="@color/white">

         

     

<!--    <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" />

        <!– 隱藏輸入法用 –>

 

        <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 android:id="@+id/citylist_layout" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">

        <textview android:background="#f0f3f5" android:gravity="center_vertical" android:layout_height="32dp" android:layout_marginleft="2dp" android:layout_width="match_parent" android:text="當前位置" android:textcolor="@color/font_color" android:textsize="16sp">

        <relativelayout android:id="@+id/current_item" android:layout_height="40dp" android:layout_width="match_parent">

            <textview android:id="@+id/current_name" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_marginleft="12dp" android:layout_width="wrap_content" android:text="定位中..." android:textcolor="@color/font_color" android:textsize="16sp">

            <textview android:id="@+id/current_size" android:layout_alignparentright="true" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_marginright="12dp" android:layout_width="wrap_content" android:text="--" android:textcolor="@color/font_color">

        </textview></textview></relativelayout>

        <textview android:background="#f0f3f5" android:gravity="center_vertical" android:layout_height="32dp" android:layout_marginleft="2dp" android:layout_width="match_parent" android:text="熱門城市" android:textcolor="@color/font_color" android:textsize="16sp">

 

        <listview android:cachecolorhint="#00000000" android:divider="#cccccc" android:dividerheight="0.5dp" android:id="@+id/hotcitylist" android:layout_height="200dip" android:layout_width="fill_parent" android:listselector="@drawable/item_selector" android:scrollingcache="false">

 

        <textview android:background="#f0f3f5" android:gravity="center_vertical" android:layout_height="32dp" android:layout_marginleft="2dp" android:layout_width="fill_parent" android:text="全國" android:textcolor="@color/font_color" android:textsize="16sp">

 

        <expandablelistview android:alwaysdrawnwithcache="false" android:cachecolorhint="#00000000" android:childdivider="@drawable/item_divider" android:divider="#cccccc" android:dividerheight="0.5dp" android:id="@+id/allcitylist" android:layout_height="fill_parent" android:layout_width="fill_parent" android:listselector="@drawable/item_selector" android:scrollbars="none" android:scrollingcache="false">

    </expandablelistview></textview></listview></textview></textview></linearlayout>

 

    <linearlayout android:id="@+id/localmap_layout" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">

 

        <textview android:background="#f0f3f5" android:gravity="center_vertical" android:layout_height="32dp" android:layout_marginleft="2dp" android:layout_width="match_parent" android:text="正在下載中" android:textcolor="@color/font_color" android:textsize="16sp">

        <listview android:cachecolorhint="#00000000" android:divider="#cccccc" android:dividerheight="0.5dp" android:id="@+id/lodinglist" android:layout_height="wrap_content" android:layout_width="match_parent" android:scrollingcache="false">

 

        </listview>

        <view android:background="#fff" android:layout_height="40dp" android:layout_width="match_parent">

        </view>

        <textview android:background="#f0f3f5" android:gravity="center_vertical" android:layout_height="32dp" android:layout_marginleft="2dp" android:layout_width="fill_parent" android:text="已下載城市 " android:textcolor="@color/font_color" android:textsize="16sp">

 

        <listview android:cachecolorhint="#00000000" android:divider="#cccccc" android:dividerheight="0.5dp" android:id="@+id/localmaplist" android:layout_height="wrap_content" android:layout_width="fill_parent" android:scrollingcache="false">

 

    </listview></textview></textview></linearlayout></button></linearlayout></imagebutton></relativelayout></linearlayout></code></code>

CityExpandableListAdapter類

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

<code class="hljs java"><code class="hljs applescript"><code class="hljs java">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;

    }

 

}</mkolsearchrecord></string,></mkolsearchrecord></string,></mkolsearchrecord></code></code></code>

三、遇到的問題

關於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。

相關文章
相關標籤/搜索