編輯:關於 Android 程式設計
本文實現一個典型的城市選擇頁面:點擊入口打開列表,右側提供字母索引快速跳轉,同時借助百度地圖定位 SDK 獲取並展示當前所在城市,用戶點擊任意城市後該城市即成為「當前城市」。
頁面分三部分:
· ListView:城市數據列表,按 A–Z 分組,組頭為字母;
· MySideBar:自定義的字母索引側邊欄,支持觸摸滑動並回調選中的字母下標;
· MapView:百度地圖定位組件,負責獲取當前城市。
為了讓列表跳轉與字母索引協同工作,需要預先建立兩張映射表:letterCharList 記錄每一行對應的字母下標(非組頭記為 -1),letterPositionList 記錄每個字母對應的列表位置。
public class CityActivity extends Activity implements MySideBar.OnTouchingLetterChangedListener {
private MapView mMapView = null;
private LocationClient mLocClient;
private LocationMode mCurrentMode;
private BitmapDescriptor mCurrentMarker;
private BaiduMap mBaiduMap;
private boolean isFirstLoc = true;
public MyLocationListenner myListener = new MyLocationListenner();
private String city;
private ListView mainList;
private List<String> data; // 數據源
private List<Integer> letterPositionList; // 每個字母所在的列表位置
private List<Integer> letterCharList; // 每行對應的字母下標,-1 表示普通行
private MySideBar myView;
private TextView tv01;
private int lastFirstVisibleItem;
private String[] title = {"GPS定位城市", "熱門城市",
"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"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.city_activity);
// ===== 定位相關初始化 =====
mMapView = (MapView) findViewById(R.id.bmapView);
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
mBaiduMap = mMapView.getMap();
mBaiduMap.setMyLocationEnabled(true);
mCurrentMode = LocationMode.NORMAL;
mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
mBaiduMap.setMyLocationConfigeration(
new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打開 GPS
option.setCoorType("bd09ll"); // 坐標類型
option.setScanSpan(1000); // 定位間隔
option.setIsNeedAddress(true); // 需要返回地址信息
option.setIsNeedLocationDescribe(true);
mLocClient.setLocOption(option);
mLocClient.start();
// ===== 列表與索引初始化 =====
mainList = (ListView) findViewById(R.id.mainlist);
myView = (MySideBar) findViewById(R.id.myview);
tv01 = (TextView) findViewById(R.id.main_tv01);
myView.setOnTouchingLetterChangedListener(this);
data = new ArrayList<String>();
letterCharList = new ArrayList<Integer>();
letterPositionList = new ArrayList<Integer>();
int index = 0, position = 0;
letterCharList.add(index);
for (int i = 0; i < ary.length; i++) {
for (int j = 0; j < ary[i].length; j++) {
if (i == 0 && j == 0) {
index++;
letterPositionList.add(position);
} else if (j == 0) {
// 每一組的第一個元素是字母組頭
letterCharList.add(index);
letterPositionList.add(position);
index++;
} else {
letterCharList.add(-1);
}
position++;
data.add(ary[i][j]);
}
}
MyAdapter adapter = new MyAdapter(this, data, letterCharList, title);
mainList.setAdapter(adapter);
// 滾動時同步更新頂部的城市提示
mainList.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) { }
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (letterCharList.get(firstVisibleItem) >= 0) {
tv01.setText("當前城市" + city);
lastFirstVisibleItem = firstVisibleItem;
} else {
if (lastFirstVisibleItem > firstVisibleItem) {
tv01.setText("當前城市" + city);
}
}
}
});
// 點擊列表項,把該城市設為當前城市
mainList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
"當前城市" + mainList.getItemAtPosition(position), 0).show();
tv01.setText((CharSequence) mainList.getItemAtPosition(position));
}
});
}
/** 側邊欄字母變化時,列表跳轉到對應位置 */
public void onTouchingLetterChanged(int s) {
mainList.setSelection(letterPositionList.get(s));
}
/**
* 數據源:按字母分組的二維數組,每組首元素為組頭。
* 下方僅列出部分分組示意,實際項目中按同樣結構補全 A–Z 即可。
*/
private String[][] ary = {
// 熱門城市
{"北京", "上海", "石家莊", "昆明", "杭州", "廣州", "成都", "西安", "南京",
"深圳", "重慶", "長沙", "沈陽", "廈門", "武漢", "海口", "烏魯木齊", "青島",
"大連", "三亞", "哈爾濱", "長春", "南寧", "貴陽", "福州", "鄭州", "濟南",
"桂林", "天津", "太原", "南昌"},
// A
{"鞍山市", "安慶市", "安陽市", "阿壩藏族羌族自治州", "安順市", "安康市",
"阿裡地區", "阿勒泰地區", "阿克蘇地區", "阿拉爾市", "阿拉善盟", "澳門特別行政區"},
// B
{"北京市", "保定市", "本溪市", "白城市", "白山市", "蚌埠市", "亳州市", "濱州市",
"白銀市", "巴中市", "畢節地區", "白沙黎族自治縣", "保亭黎族苗族自治縣",
"保山市", "寶雞市", "百色市", "北海市", "博爾塔拉蒙古自治州",
"巴音郭楞蒙古自治州", "包頭市", "巴彥淖爾市"},
// C
{"長沙市", "承德市", "滄州市", "朝陽市", "常州市", "滁州市", "巢湖市", "池州市",
"郴州市", "常德市", "潮州市", "成都市", "澄邁縣", "昌江黎族自治縣",
"楚雄彝族自治州", "崇左市", "昌都地區", "昌吉回族自治州", "赤峰市"},
// D
{"大同市", "大連市", "丹東市", "大興安嶺地區", "大慶市", "德州市", "東營市",
"東莞市", "定西市", "達州市", "德陽市", "儋州市", "東方市", "定安縣",
"德宏傣族景頗族自治州", "大理白族自治州", "迪慶藏族自治州"},
// ... E / F / G / H 等其餘分組結構相同,此處省略
// I、O、U、V 等無對應城市的字母可填 {"暫無"}
// Z
{"重慶市", "張家口市", "長治市", "長春市", "鎮江市", "舟山市", "漳州市", "淄博市",
"棗莊市", "鄭州市", "周口市", "駐馬店市", "株洲市", "張家界市", "珠海市",
"肇慶市", "湛江市", "中山市", "張掖市", "自貢市", "資陽市", "遵義市",
"昭通市", "中衛市"}
};
/** 定位回調 */
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 銷毀後不再處理新位置
if (location == null || mMapView == null) {
return;
}
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
.direction(100) // 順時針 0-360
.latitude(location.getLatitude())
.longitude(location.getLongitude())
.build();
city = location.getCity();
tv01.setText(city); // 展示當前定位城市
mBaiduMap.setMyLocationData(locData);
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
MapStatus.Builder builder = new MapStatus.Builder();
builder.target(ll).zoom(18.0f);
mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
}
}
public void onReceivePoi(BDLocation poiLocation) { }
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocClient.stop();
mBaiduMap.setMyLocationEnabled(false);
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
}
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<ListView
android:id="@+id/mainlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:cacheColorHint="#00000000"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dip"
android:scrollbars="none" />
<TextView
android:id="@+id/main_tv01"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:background="#F0F0F0"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:textColor="#ff55bb22"
android:textSize="20sp" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.test0504.MySideBar
android:id="@+id/myview"
android:layout_width="30dip"
android:layout_height="fill_parent"
android:layout_gravity="right" />
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:visibility="gone" />
</FrameLayout>
</FrameLayout>
列表項佈局則由一個豎向 LinearLayout 構成,包含字母組頭樣式的 TextView 與城市名 TextView 兩個控件。
核心邏輯在 dispatchTouchEvent() 中:把觸摸的 Y 坐標按控件高度等分成 28 份(「定位」「熱」+ A–Z),算出對應的字母下標並回調,同時記錄選中項以便 onDraw() 高亮顯示。
public class MySideBar extends View {
OnTouchingLetterChangedListener onTouchingLetterChangedListener;
private boolean showBkg;
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"};
/** 被選中位置 */
int choose = -1;
private Paint paint = new Paint();
public MySideBar(Context context) {
super(context);
}
public MySideBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MySideBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (showBkg) {
canvas.drawColor(Color.parseColor("#ccddFF"));
}
float height = getHeight();
float width = getWidth();
// 單個字母的高度
float singleHeight = height / (float) (b.length);
for (int i = 0; i < b.length; i++) {
paint.setColor(Color.BLACK);
paint.setTextSize(20);
if (i == choose) {
paint.setColor(Color.parseColor("#3399ff"));
paint.setFakeBoldText(true); // 選中加粗
}
float xPos = width / 2 - paint.measureText(b[i]) / 2;
float yPos = singleHeight * i + singleHeight;
canvas.drawText(b[i], xPos, yPos, paint);
paint.reset();
}
}
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
float y = event.getY();
final int oldChoose = choose;
// 按高度等分換算字母下標
final int c = (int) (y / getHeight() * b.length);
final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;
switch (action) {
case MotionEvent.ACTION_DOWN:
showBkg = true;
if (oldChoose != c && listener != null && c >= 0 && c < b.length) {
listener.onTouchingLetterChanged(c);
choose = c;
invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
if (oldChoose != c && listener != null && c >= 0 && c < b.length) {
listener.onTouchingLetterChanged(c);
choose = c;
invalidate();
}
break;
case MotionEvent.ACTION_UP:
showBkg = false;
choose = -1;
invalidate();
break;
}
return true;
}
public void setOnTouchingLetterChangedListener(
OnTouchingLetterChangedListener onTouchingLetterChangedListener) {
this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;
}
public interface OnTouchingLetterChangedListener {
void onTouchingLetterChanged(int s);
}
}
定位相關權限不可少,同時需要註冊百度定位服務與 API Key:
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.test0504"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" />
<!-- 網絡定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- GPS 定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- WiFi 信息,用於網絡定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 運營商信息 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 手機當前狀態 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 寫入離線定位數據 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 網絡定位需要上網 -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name=".CityActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" />
<meta-data android:name="com.baidu.lbsapi.API_KEY"
android:value="你的API_KEY" />
</application>
</manifest>
1. API Key 請自行申請並替換,不要沿用示例中的值,否則定位會失敗。
2. targetSdkVersion 建議提升到 23 以上,此時上述危險權限必須在運行時動態申請,否則在 Android 6.0 及以上設備上會直接拿到空數據。
3. MapView 的生命週期必須托管:onResume() 中調 mMapView.onResume(),onPause() 中調 mMapView.onPause(),onDestroy() 中調 mMapView.onDestroy(),同時停止定位並關閉定位圖層。
4. 字母索引的兩張映射表是關鍵。letterCharList 決定滾動時能否正確顯示分組標題,letterPositionList 決定點擊字母後 setSelection() 的落點,兩者與 ary 的結構必須嚴格對應。
5. 若城市數據量大,建議把 ary 移到 assets 或本地數據庫中讀取,避免代碼文件過於龐大。
Android 虛擬鍵盤彈出遮擋登入按鈕的解決方案
在 Android 應用中,虛擬鍵盤的彈起往往會遮擋住介面上的部分元件。雖然我們可以透過在清單檔(Manifest)中設定相關屬性,讓版面隨著鍵盤彈出而自動上推,但這種做
在 Android 上復刻 iOS 相機模式的滑動切換動畫
iOS 的動畫水準一直是它相對 Android 的優勢之一。相機裡切換拍攝模式時,那個帶 3D 透視感的橫向滑動就頗有講究——文字有縱深感,但相鄰兩組之間的間距在滑動過程
Android WebP:縮小 APK 體積的圖片優化方案
WebP 是 Google 推出的圖片格式,能在保持良好畫質的同時提供更高的壓縮效率。對於 Android 應用而言,將 PNG 或 JPG 圖片轉為 WebP,是縮小
Android SQLite 開發詳解:CRUD、Cursor 與 SQLiteOpenHelper
SQLite 在 Android 中的基本操作Android 內建 SQLite,適合儲存結構化資料。開發者可透過 openOrCreateDatabase 建立或開啟資