很少囉嗦,先上圖,再上代碼java
這是進入後的主界面,會自動定位到本身的當前位置:
android
這是點擊上方選擇城市的界面,城市是按照首字母排好序的,能夠輸入關鍵字搜索,也能夠點擊旁邊的字母索引搜索:
git
這是選擇城市後的界面:
canvas
這是點擊搜索位置懸浮框後的界面,每頁展現十條數據,能夠下拉刷新和加載更多:
api
這是點擊搜索的位置的某一項後展現的界面,首先會在地圖上標示出來,而後會在下面懸浮一個框展現選擇的位置的名字和地址,點擊肯定就能夠拿到該位置的地址+名字:
app
也能夠在地圖頁面隨意點擊,都會在下面懸浮框展現並在地圖上標識出來:
ide
功能基本上就是上面圖片所展現的,雖然比較簡單,但仍是能學到不少東西的,這也是本人第一次使用百度地圖sdk,功能仍是很強大,至於怎樣導入百度sdk什麼的拒不回答,本身看百度傻瓜教程去,下面開始上主要代碼:佈局
這是主界面的佈局文件:測試
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main_content" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFFFFFFF" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="50dp" android:background="@color/robin_title_bg" > <ImageView android:id="@+id/robin_title_left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:padding="10dp" android:src="@drawable/nav_back" /> <LinearLayout android:id="@+id/ll_select_city" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:orientation="horizontal" > <TextView android:id="@+id/robin_title_center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="3dp" android:text="測試" android:textColor="@color/robin_white" android:textSize="@dimen/robin_font_bigger" /> <ImageView android:layout_width="18dp" android:layout_height="18dp" android:paddingTop="3dp" android:src="@drawable/schedule_city_select" /> </LinearLayout> <TextView android:id="@+id/robin_title_right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:padding="10dp" android:text="測試" android:textColor="@color/robin_white" android:textSize="@dimen/robin_font_big" /> </RelativeLayout> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.baidu.mapapi.map.MapView android:id="@+id/bmapView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:clickable="true" /> <EditText android:id="@+id/location_edit" android:layout_width="fill_parent" android:layout_height="40dp" android:layout_alignParentTop="true" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="8dip" android:background="@color/bottom_bar_normal_bg" android:drawableLeft="@drawable/search_bar_icon_normal" android:editable="false" android:hint="輸入搜索關鍵字" android:paddingBottom="5dp" android:paddingLeft="10dp" android:paddingTop="5dp" android:singleLine="true" android:textSize="15.0dip" /> <RelativeLayout android:id="@+id/rl_location_detail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="10dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:background="@drawable/list_card_bg" android:visibility="gone" > <TextView android:id="@+id/tv_location_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:paddingTop="12dp" android:text="A" android:singleLine="true" android:textColor="@color/robin_black" android:textSize="@dimen/robin_font_big" /> <TextView android:id="@+id/tv_location_address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="10dp" android:layout_marginTop="6dp" android:paddingBottom="12dp" android:layout_below="@id/tv_location_name" android:singleLine="true" android:text="hhhh" android:textColor="@color/robin_gray" android:textSize="@dimen/robin_font_normal" /> <Button android:id="@+id/bt_finish" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:padding="10dp" android:background="@color/robin_title_bg" android:layout_below="@id/tv_location_address" android:layout_centerHorizontal="true" android:gravity="center" android:text="肯定" android:textColor="@color/robin_white" android:textSize="@dimen/robin_font_big" /> </RelativeLayout> </RelativeLayout> </LinearLayout>
主界面代碼:ui
package com.haoqi.robin.schedule.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BaiduMap.OnMapClickListener; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.MapPoi; import com.baidu.mapapi.map.MapStatus; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.search.core.SearchResult; import com.baidu.mapapi.search.geocode.GeoCodeResult; import com.baidu.mapapi.search.geocode.GeoCoder; import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption; import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; import com.baidu.mapapi.search.poi.PoiSearch; import com.haoqi.robin.R; import com.haoqi.robin.RobinApplication; import com.haoqi.robin.schedule.bean.ScheduleCityGpsStruct; /** * 獲取位置功能 */ public class ScheduleLocationSearchActivity extends FragmentActivity implements OnGetGeoCoderResultListener { protected static final int SELECTCITY = 0; protected static final int SEARCH_POI = 1; GeoCoder mSearch = null; private EditText location_edit; private String city; private LatLng location; private MapView mMapView; private BaiduMap mBaiduMap; private int load_Index = 0; private String strAddress; private TextView tvTitle; private String poiName=""; private TextView tv_location_name; private TextView tv_location_address; private RelativeLayout rl_location_detail; private String poiAddress; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.schedule_location_list_activity); initTitle(); initView(); // 初始化搜索模塊,註冊搜索事件監聽 mSearch = GeoCoder.newInstance(); mSearch.setOnGetGeoCodeResultListener(this); location = new LatLng(RobinApplication.dLat, RobinApplication.dLon); mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(location)); mBaiduMap = mMapView.getMap(); mMapView.showZoomControls(false); MapStatus mMapStatus = new MapStatus.Builder() .target(location) .zoom(16) .build(); mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mMapStatus)); //構建Marker圖標 BitmapDescriptor bitmap = BitmapDescriptorFactory .fromResource(R.drawable.bmap_icon_gcoding); //構建MarkerOption,用於在地圖上添加Marker OverlayOptions option = new MarkerOptions() .position(location) .icon(bitmap); //在地圖上添加Marker,並顯示 mBaiduMap.addOverlay(option); mBaiduMap.setOnMapClickListener(new OnMapClickListener() { @Override public boolean onMapPoiClick(MapPoi arg0) { mBaiduMap.clear(); BitmapDescriptor bitmap = BitmapDescriptorFactory .fromResource(R.drawable.bmap_icon_marka); //構建MarkerOption,用於在地圖上添加Marker OverlayOptions option = new MarkerOptions() .position(arg0.getPosition()) .icon(bitmap); //在地圖上添加Marker,並顯示 mBaiduMap.addOverlay(option); poiName = arg0.getName(); mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(arg0.getPosition())); rl_location_detail.setVisibility(View.VISIBLE); tv_location_name.setVisibility(View.VISIBLE); tv_location_name.setText(poiName); tv_location_address.setText(poiAddress); return true; } @Override public void onMapClick(LatLng arg0) { mBaiduMap.clear(); BitmapDescriptor bitmap = BitmapDescriptorFactory .fromResource(R.drawable.bmap_icon_marka); //構建MarkerOption,用於在地圖上添加Marker OverlayOptions option = new MarkerOptions() .position(arg0) .icon(bitmap); //在地圖上添加Marker,並顯示 mBaiduMap.addOverlay(option); mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(arg0)); rl_location_detail.setVisibility(View.VISIBLE); tv_location_name.setVisibility(View.GONE); tv_location_address.setText(poiAddress); } }); location_edit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(ScheduleLocationSearchActivity.this, ScheduleSearchCityPoiActivity.class); i.putExtra("city", city); startActivityForResult(i, SEARCH_POI); } }); } private void initTitle() { ImageView imgBack = (ImageView) findViewById(R.id.robin_title_left); imgBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); tvTitle = (TextView) findViewById(R.id.robin_title_center); tvTitle.setText("位置"); tvTitle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(ScheduleLocationSearchActivity.this,ScheduleSelectCityActivity.class); startActivityForResult(i, SELECTCITY); } }); TextView tvRight = (TextView) findViewById(R.id.robin_title_right); tvRight.setText("完成"); tvRight.setVisibility(View.GONE); } private void initView() { location_edit = (EditText) findViewById(R.id.location_edit); mMapView = (MapView) findViewById(R.id.bmapView); tv_location_name = (TextView) findViewById(R.id.tv_location_name); tv_location_address = (TextView) findViewById(R.id.tv_location_address); rl_location_detail = (RelativeLayout) findViewById(R.id.rl_location_detail); Button bt_finish = (Button) findViewById(R.id.bt_finish); bt_finish.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(); String address = tv_location_address.getText().toString().trim(); String name; if (tv_location_name.isShown()) { name = tv_location_name.getText().toString().trim(); }else { name = ""; } i.putExtra("location", address+name); setResult(RESULT_OK, i); finish(); } }); } @Override public void onGetGeoCodeResult(GeoCodeResult result) { } @Override public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) { if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) { Toast.makeText(ScheduleLocationSearchActivity.this, "抱歉,未能找到結果", Toast.LENGTH_LONG).show(); return; } poiAddress = result.getAddress(); city = result.getAddressDetail().city; strAddress = result.getAddress()+poiName; tvTitle.setText(city); } @Override protected void onPause() { mMapView.onPause(); super.onPause(); } @Override protected void onResume() { mMapView.onResume(); super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); mBaiduMap.clear(); mMapView.onDestroy(); mSearch.destroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SELECTCITY && resultCode == RESULT_OK) { //選擇城市 ScheduleCityGpsStruct struct = (ScheduleCityGpsStruct) data.getSerializableExtra("cityItemData"); String strCityName = struct.getStrCityName(); rl_location_detail.setVisibility(View.GONE); LatLng selectedCity = new LatLng(Double.parseDouble(struct.getStrLatitude()), Double.parseDouble(struct.getStrLongitude())); MapStatus mMapStatus = new MapStatus.Builder() .target(selectedCity) .zoom(12) .build(); mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mMapStatus)); mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(selectedCity)); }else if (requestCode == SEARCH_POI && resultCode == RESULT_OK) { //搜索位置 if (data != null) { String searchPoiAddress = data.getStringExtra("address"); poiName = data.getStringExtra("name"); double latitude = data.getExtras().getDouble("latitude"); double longitude = data.getExtras().getDouble("longitude"); LatLng poiLocation = new LatLng(latitude, longitude); rl_location_detail.setVisibility(View.VISIBLE); tv_location_name.setVisibility(View.VISIBLE); tv_location_name.setText(poiName); tv_location_address.setText(searchPoiAddress); mBaiduMap.clear(); MapStatus mMapStatus = new MapStatus.Builder() .target(poiLocation) .zoom(16) .build(); mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mMapStatus)); BitmapDescriptor bitmap = BitmapDescriptorFactory .fromResource(R.drawable.bmap_icon_marka); //構建MarkerOption,用於在地圖上添加Marker OverlayOptions option = new MarkerOptions() .position(poiLocation) .icon(bitmap); //在地圖上添加Marker,並顯示 mBaiduMap.addOverlay(option); mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(poiLocation)); } } } }
選擇城市代碼:
package com.haoqi.robin.schedule.activity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import com.haoqi.robin.R; import com.haoqi.robin.schedule.adapter.ScheduleCitySelectAdapter; import com.haoqi.robin.schedule.bean.ScheduleCityGpsStruct; import com.haoqi.robin.ui.contact.ClearEditText; import com.haoqi.robin.ui.contact.SideBar; import com.haoqi.robin.ui.contact.SideBar.OnTouchingLetterChangedListener; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class ScheduleSelectCityActivity extends Activity { private ListView sortListView; private SideBar sideBar; private TextView dialog; private ClearEditText mClearEditText; private List<ScheduleCityGpsStruct> cityList, currentCityList; private ScheduleCitySelectAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.schedule_select_city_activity); initTitle(); initView(); loadData(); } private void initTitle() { ImageView imgBack = (ImageView) findViewById(R.id.robin_title_left); imgBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); TextView tvTitle = (TextView) findViewById(R.id.robin_title_center); tvTitle.setText("選擇城市"); TextView tvRight = (TextView) findViewById(R.id.robin_title_right); tvRight.setVisibility(View.GONE); } private void initView() { sideBar = (SideBar) findViewById(R.id.city_sidrbar); dialog = (TextView) findViewById(R.id.dialog); sideBar.setTextView(dialog); sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() { @Override public void onTouchingLetterChanged(String s) { int position = adapter.getPositionForSection(s); if (position != -1) { sortListView.setSelection(position); } } }); sortListView = (ListView) findViewById(R.id.city_lvcountry); sortListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ScheduleCityGpsStruct struct = currentCityList.get(position); Intent i = new Intent(); Bundle bundle = new Bundle(); bundle.putSerializable("cityItemData", struct); i.putExtras(bundle); setResult(RESULT_OK, i); finish(); } }); mClearEditText = (ClearEditText) findViewById(R.id.city_filter_edit); mClearEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { filterData(s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); } private void loadData() { cityList = new ArrayList<ScheduleCityGpsStruct>(); try { InputStream is = getAssets().open("city_gps.txt"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = ""; String[] arrs = null; while ((line = br.readLine()) != null) { ScheduleCityGpsStruct sGpsStruct = new ScheduleCityGpsStruct(); arrs = line.split(","); if (arrs.length == 4) { sGpsStruct.setSortLetters(arrs[0]); sGpsStruct.setStrCityName(arrs[1]); sGpsStruct.setStrLongitude(arrs[2]); sGpsStruct.setStrLatitude(arrs[3]); }else if (arrs.length == 3) { sGpsStruct.setSortLetters(""); sGpsStruct.setStrCityName(arrs[0]); sGpsStruct.setStrLongitude(arrs[1]); sGpsStruct.setStrLatitude(arrs[2]); } cityList.add(sGpsStruct); } br.close(); isr.close(); is.close(); currentCityList = cityList; adapter = new ScheduleCitySelectAdapter(this, cityList); sortListView.setAdapter(adapter); } catch (IOException e) { e.printStackTrace(); } } private void filterData(String filterStr) { List<ScheduleCityGpsStruct> filterDateList = new ArrayList<ScheduleCityGpsStruct>(); if (TextUtils.isEmpty(filterStr)) { filterDateList = cityList; } else { filterDateList.clear(); for (ScheduleCityGpsStruct struct : cityList) { String strCityName = struct.getStrCityName(); if (strCityName.contains(filterStr.toString())) { filterDateList.add(struct); } } currentCityList = filterDateList; } adapter.updateListView(filterDateList); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { finish(); return true; } return super.onKeyDown(keyCode, event); } }
選擇城市的適配器代碼:
package com.haoqi.robin.schedule.adapter; import java.util.List; import com.haoqi.robin.R; import com.haoqi.robin.schedule.bean.ScheduleCityGpsStruct; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SectionIndexer; import android.widget.TextView; public class ScheduleCitySelectAdapter extends BaseAdapter implements SectionIndexer { private List<ScheduleCityGpsStruct> list = null; private Context mContext; public ScheduleCitySelectAdapter(Context mContext, List<ScheduleCityGpsStruct> list) { this.mContext = mContext; this.list = list; } /** * @param list */ public void updateListView(List<ScheduleCityGpsStruct> list) { this.list = list; notifyDataSetChanged(); } public int getCount() { return this.list.size(); } public Object getItem(int position) { return list.get(position); } public long getItemId(int position) { return position; } public View getView(final int position, View view, ViewGroup arg2) { ViewHolder viewHolder = null; if (view == null) { viewHolder = new ViewHolder(); view = LayoutInflater.from(mContext).inflate( R.layout.schedule_select_city_item, null); viewHolder.tvTitle = (TextView) view .findViewById(R.id.city_list_item_name); viewHolder.tvLetter = (TextView) view .findViewById(R.id.city_list_item_catalog); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } ScheduleCityGpsStruct struct = list.get(position); // 首字母 String sortLetters = struct.getSortLetters(); if (sortLetters != null && sortLetters.length() > 0) { if (position == getPositionForSection(position, sortLetters)) { viewHolder.tvLetter.setVisibility(View.VISIBLE); viewHolder.tvLetter.setText(sortLetters); } }else { viewHolder.tvLetter.setVisibility(View.GONE); } viewHolder.tvTitle.setText(struct.getStrCityName()); return view; } final static class ViewHolder { TextView tvLetter; TextView tvTitle; } public int getPositionForSection(String section) { for (int i = 0; i < getCount(); i++) { String sortStr = list.get(i).getSortLetters(); if (section.equals(sortStr)) { return i; } } return -1; } public int getPositionForSection(int iPosition, String section) { for (int i = 0; i < getCount(); i++) { String sortStr = list.get(i).getSortLetters(); if (section.equals(sortStr)) { return i; } } return -1; } @Override public Object[] getSections() { return null; } @Override public int getPositionForSection(int sectionIndex) { return 0; } @Override public int getSectionForPosition(int position) { return 0; } }
查找城市內poi的代碼:
package com.haoqi.robin.schedule.activity; import java.util.ArrayList; import java.util.List; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.search.core.CityInfo; import com.baidu.mapapi.search.core.PoiInfo; import com.baidu.mapapi.search.core.SearchResult; import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener; import com.baidu.mapapi.search.poi.PoiCitySearchOption; import com.baidu.mapapi.search.poi.PoiDetailResult; import com.baidu.mapapi.search.poi.PoiResult; import com.baidu.mapapi.search.poi.PoiSearch; import com.haoqi.robin.R; import com.haoqi.robin.schedule.adapter.ScheduleSearchCityPoiAdapter; import com.haoqi.robin.ui.ProgressView; import com.haoqi.robin.ui.XListView; import com.haoqi.robin.ui.XListView.IXListViewListener; import com.haoqi.robin.ui.contact.ClearEditText; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class ScheduleSearchCityPoiActivity extends Activity implements OnGetPoiSearchResultListener{ private XListView poiListView; private ClearEditText mSearchEditText; private PoiSearch mPoiSearch = null; private int load_Index = 0; private List<PoiInfo> poiList; private ScheduleSearchCityPoiAdapter adapter; private ProgressView pgLoading; private Boolean bLoading = false; private String keyWord; private String city; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.schedule_search_city_poi_activity); city = getIntent().getStringExtra("city"); mPoiSearch = PoiSearch.newInstance(); mPoiSearch.setOnGetPoiSearchResultListener(this); initTitle(); initView(); } private void initTitle() { ImageView imgBack = (ImageView) findViewById(R.id.robin_title_left); imgBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); TextView tvTitle = (TextView) findViewById(R.id.robin_title_center); tvTitle.setText("查找位置"); TextView tvRight = (TextView) findViewById(R.id.robin_title_right); tvRight.setVisibility(View.VISIBLE); tvRight.setText("搜索"); tvRight.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { keyWord = mSearchEditText.getText().toString().trim(); hideKeyboard(); if (keyWord != null && keyWord.length() > 0) { pgLoading.setVisibility(View.VISIBLE); loadData(keyWord); } else { Toast.makeText(getApplicationContext(), "您尚未輸入搜索地點", 0) .show(); return; } } }); } private void initView() { pgLoading = (ProgressView) findViewById(R.id.search_poi_progress); mSearchEditText = (ClearEditText) findViewById(R.id.pio_filter_edit); poiListView = (XListView) findViewById(R.id.schedule_search_pio); poiList = new ArrayList<PoiInfo>(); } private void loadData(String keyWord) { load_Index = 0; mPoiSearch.searchInCity((new PoiCitySearchOption()).city(city) .keyword(keyWord).pageNum(load_Index)); } protected void loadMoreData() { load_Index++; mPoiSearch.searchInCity((new PoiCitySearchOption()).city(city) .keyword(keyWord).pageNum(load_Index)); } @Override public void onGetPoiDetailResult(PoiDetailResult result) { if (result.error != SearchResult.ERRORNO.NO_ERROR) { Toast.makeText(ScheduleSearchCityPoiActivity.this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ScheduleSearchCityPoiActivity.this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT).show(); } } @Override public void onGetPoiResult(PoiResult result) { pgLoading.loadSuccess(); pgLoading.setVisibility(View.GONE); poiListView.setVisibility(View.VISIBLE); if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) { Toast.makeText(ScheduleSearchCityPoiActivity.this, "未找到結果", Toast.LENGTH_LONG).show(); stopRefresh(); return; } if (result.error == SearchResult.ERRORNO.NO_ERROR) { List<PoiInfo> allPoi = result.getAllPoi(); if (adapter != null) { if (load_Index == 0) {//刷新 refreshPoiList(allPoi); }else { updatePoiList(allPoi); } }else { bLoading = false; renderPoiList(allPoi); } return; } if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) { // 當輸入關鍵字在本市沒有找到,但在其餘城市找到時,返回包含該關鍵字信息的城市列表 String strInfo = "在"; for (CityInfo cityInfo : result.getSuggestCityList()) { strInfo += cityInfo.city; strInfo += ","; } strInfo += "找到結果"; Toast.makeText(ScheduleSearchCityPoiActivity.this, strInfo, Toast.LENGTH_LONG).show(); stopRefresh(); } } private void refreshPoiList(List<PoiInfo> allPoi) { poiList.clear(); poiList.addAll(allPoi); adapter.notifyDataSetChanged(); stopRefresh(); } private void renderPoiList(List<PoiInfo> allPoi) { poiList = allPoi; adapter = new ScheduleSearchCityPoiAdapter( ScheduleSearchCityPoiActivity.this, poiList); poiListView.setAdapter(adapter); poiListView.setPullRefreshEnable(true); poiListView.setPullLoadEnable(true); poiListView.setXListViewListener(new IXListViewListener() { @Override public void onRefresh() { if (bLoading) return; bLoading = true; loadData(keyWord); } @Override public void onLoadMore() { if (bLoading) return; bLoading = true; loadMoreData(); } }); poiListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { PoiInfo poiInfo = poiList.get(position-1); String strAddress = poiInfo.address; String strName = poiInfo.name; LatLng location = poiInfo.location; Intent intent = new Intent(); intent.putExtra("address", strAddress); intent.putExtra("name", strName); intent.putExtra("latitude", location.latitude); intent.putExtra("longitude", location.longitude); setResult(RESULT_OK, intent); finish(); } }); } private void updatePoiList(List<PoiInfo> allPoi) { poiList.addAll(allPoi); adapter.notifyDataSetChanged(); stopRefresh(); } private void stopRefresh(){ poiListView.stopLoadMore(); poiListView.stopRefresh(); bLoading = false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { finish(); return true; } return super.onKeyDown(keyCode, event); } /** * 隱藏軟鍵盤 */ private void hideKeyboard() { InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getCurrentFocus() != null) manager.hideSoftInputFromWindow(getCurrentFocus() .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } @Override protected void onDestroy() { super.onDestroy(); mPoiSearch.destroy(); } }
大概就是這麼多了,有須要的能夠借鑑參考一下,互相交流,共同進步,大神勿笑。另外,在城市列表那個我是讀取的assets目錄裏的一個txt文件,裏面是城市和其對應的座標。
城市列表旁邊那個索引用的是自定義的sideBar,也是網上下載的,代碼以下:
package com.haoqi.robin.ui.contact; import com.haoqi.robin.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; public class SideBar extends View { // �����¼� private OnTouchingLetterChangedListener onTouchingLetterChangedListener; // 26����ĸ public static String[] b = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#" }; private int choose = -1;// ѡ�� private Paint paint = new Paint(); private TextView mTextDialog; public void setTextView(TextView mTextDialog) { this.mTextDialog = mTextDialog; } public SideBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public SideBar(Context context, AttributeSet attrs) { super(context, attrs); } public SideBar(Context context) { super(context); } /** * ��д������� */ protected void onDraw(Canvas canvas) { super.onDraw(canvas); // ��ȡ����ı䱳����ɫ. int height = getHeight();// ��ȡ��Ӧ�߶� int width = getWidth(); // ��ȡ��Ӧ��� int singleHeight = height / b.length;// ��ȡÿһ����ĸ�ĸ߶� for (int i = 0; i < b.length; i++) { paint.setColor(Color.rgb(33, 65, 98)); // paint.setColor(Color.WHITE); paint.setTypeface(Typeface.DEFAULT_BOLD); paint.setAntiAlias(true); paint.setTextSize(25); // ѡ�е�״̬ if (i == choose) { paint.setColor(Color.parseColor("#3399ff")); paint.setFakeBoldText(true); } // x�������м�-�ַ��ȵ�һ��. float xPos = width / 2 - paint.measureText(b[i]) / 2; float yPos = singleHeight * i + singleHeight; canvas.drawText(b[i], xPos, yPos, paint); paint.reset();// ���û��� } } @Override public boolean dispatchTouchEvent(MotionEvent event) { final int action = event.getAction(); final float y = event.getY(); final int oldChoose = choose; final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener; final int c = (int) (y / getHeight() * b.length); switch (action) { case MotionEvent.ACTION_UP: setBackgroundDrawable(new ColorDrawable(0x00000000)); choose = -1;// invalidate(); if (mTextDialog != null) { mTextDialog.setVisibility(View.INVISIBLE); } break; default: setBackgroundResource(R.drawable.sidebar_background); if (oldChoose != c) { if (c >= 0 && c < b.length) { if (listener != null) { listener.onTouchingLetterChanged(b[c]); } if (mTextDialog != null) { mTextDialog.setText(b[c]); mTextDialog.setVisibility(View.VISIBLE); } choose = c; invalidate(); } } break; } return true; } /** * * @param onTouchingLetterChangedListener */ public void setOnTouchingLetterChangedListener( OnTouchingLetterChangedListener onTouchingLetterChangedListener) { this.onTouchingLetterChangedListener = onTouchingLetterChangedListener; } /** * �ӿ� * * @author coder * */ public interface OnTouchingLetterChangedListener { public void onTouchingLetterChanged(String s); } }
搜索城市裏poi那個界面用的是支持下拉刷新和加載的XListView控件,差很少代碼都貼出來了,暫時就這麼多。