Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android使用自定控件實現城市列表展示並且實現當前城市定位

android使用自定控件實現城市列表展示並且實現當前城市定位

編輯:關於Android編程

自定義控件,點擊控件,展示城市列表,使用百度地圖定位當前城市,並且展示當前城市
代碼類
package com.example.test0504;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.model.LatLng;
import com.example.adapter.MyAdapter;
import com.example.test0504.MainActivity.MyLocationListenner;


/**
 * 
 * 定義城市頁面
 * @author 淺議愛
 *
 */
public class CityActivity extends Activity implements
    MySideBar.OnTouchingLetterChangedListener {

    //定義控件
    MapView mMapView = null;      
    // 定位相關
    LocationClient mLocClient;
    //配置定位圖層顯示方式
    private LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    //定義 BaiduMap 地圖對象的操作方法與接口
    BaiduMap mBaiduMap;
    boolean isFirstLoc = true; // 是否首次定位
    public MyLocationListenner myListener = new MyLocationListenner();

    private String city;



    private ListView mainList;
    /** 數據源 */
    private List data;
    /** 字母位置 */
    private List letterPositionList;
    /** 字母Char */
    private List letterCharList;
    private MySideBar myView;
    private TextView tv01;
    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" };
    private int lastFirstVisibleItem;


  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    SDKInitializer.initialize(getApplicationContext());
    setContentView(R.layout.city_activity);

    //或得上一個頁面傳遞過來的城市名稱(這裡指的是當前定位的城市名)
//  Intent it=getIntent();
//  final String tv=(String) it.getSerializableExtra("city");


     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();
        letterCharList = new ArrayList();
        letterPositionList = new ArrayList();

        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(title[letterCharList.get(firstVisibleItem)]);
                    tv01.setText("當前城市"+city);//設置值
                    lastFirstVisibleItem = firstVisibleItem;
                } else {    
                    if (lastFirstVisibleItem > firstVisibleItem) {
//                      tv01.setText(title[letterCharList
//                              .get(lastFirstVisibleItem) - 1]);
                        tv01.setText("當前城市"+city);//設置值
                    }
                }
            }
        });

        //點擊item項,轉換成要定位的城市
        mainList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView parent, View view,
                int position, long id) {

//          Toast.makeText(getApplicationContext(), mainList.getItemAtPosition(position)+"我被點擊了。。。", 0).show();
            Toast.makeText(getApplicationContext(), "當前城市"+mainList.getItemAtPosition(position),0).show();
            tv01.setText((CharSequence) mainList.getItemAtPosition(position));//將城市定位的位置換成點擊的城市
        }
    });
    }


    public void onTouchingLetterChanged(int s) {
        mainList.setSelection(letterPositionList.get(s));
    }

    /** 數據源二維數組 */
    private String[][] ary = {

//          {"正在定位..."},
            // 熱門城市
            { "北京", "上海", "石家莊", "昆明", "杭州", "廣州", "成都", "西安", "南京", "深圳",
                    "重慶", "長沙", "沈陽", "廈門", "武漢", "海口", "烏魯木齊", "青島", "大連",
                    "三亞", "哈爾濱", "長春", "南寧", "貴陽", "福州", "鄭州", "濟南", "桂林",
                    "天津", "太原", "南昌" },
            // 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

            { "重慶市", "張家口市", "長治市", "長春市", "鎮江市", "舟山市", "漳州市", "淄博市", "棗莊市",
                    "鄭州市", "周口市", "駐馬店市", "株洲市", "張家界市", "珠海市", "肇慶市", "湛江市",
                    "中山市", "張掖市", "自貢市", "資陽市", "遵義市", "昭通市", "中衛市" } };
     public class MyLocationListenner implements BDLocationListener {

            @Override
            public void onReceiveLocation(BDLocation location) {
                // map view 銷毀後不在處理新接收的位置
                if (location == null || mMapView == null) {
                    return;
                }
//              tv_map.setText("[我的位置]\n" + location.getStreet());
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                                // 此處設置開發者獲取到的方向信息,順時針0-360
                        .direction(100).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();

                //定位當前城市   
                city=location.getCity();
                tv01.setText(city);//將當前定位的城市設置給textview
                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();
            // 在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命周期管理
            mLocClient.stop();
            //定位層關閉
            mBaiduMap.setMyLocationEnabled(false);
        }

        @Override
        protected void onResume() {
            super.onResume();
            // 在activity執行onResume時執行mMapView. onResume (),實現地圖生命周期管理
            mMapView.onResume();
        }

        @Override
        protected void onPause() {
            super.onPause();
            // 在activity執行onPause時執行mMapView. onPause (),實現地圖生命周期管理
            mMapView.onPause();
        }

}
布局文件


<framelayout android:background="#ffffff" android:layout_height="fill_parent" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
    

    

            

     

 </framelayout>

自定義view
package com.example.test0504;

import android.content.Context;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.Paint;
 import android.util.AttributeSet;
 import android.view.MotionEvent;
 import android.view.View;

 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, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MySideBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    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) {
                if (c >= 0 && c < b.length) {
                    listener.onTouchingLetterChanged(c);
                    choose = c;
                    invalidate();
                }
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (oldChoose != c && listener != null) {
                if (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 {
        public void onTouchingLetterChanged(int s);
    }
 }
配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://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"></uses-permission>
        <!-- 這個權限用於訪問GPS定位-->
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
        <!-- 用於訪問wifi網絡信息,wifi信息會用於進行網絡定位-->
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
        <!-- 獲取運營商信息,用於支持提供運營商信息相關的接口-->
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
        <!-- 這個權限用於獲取wifi的獲取權限,wifi信息會用來進行網絡定位-->
        <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
        <!-- 用於讀取手機當前的狀態-->
        <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
        <!-- 寫入擴展存儲,向擴展卡寫入數據,用於寫入離線定位數據-->
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
        <!-- 訪問網絡,網絡定位需要上網-->
        <uses-permission android:name="android.permission.INTERNET" />
        <!-- SD卡讀取權限,用戶寫入離線定位數據-->
        <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>


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

        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="ZVqLlEhHMY8LSzD4GpK8gezEuP0CCDgs" />


    </application>

</manifest>


布局文件
<?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" >

     <TextView
         android:id="@+id/mainlist_item_tv01"
         android:layout_width="fill_parent"
         android:layout_height="30dp"
         android:background="#F0F0F0"
         android:gravity="center_vertical"
         android:paddingLeft="10dp"
         android:textColor="#ff55bb22"
         android:text="test"
         android:textSize="20sp" />

     <TextView
         android:id="@+id/mainlist_item_tv02"
         android:layout_width="fill_parent"
         android:layout_height="40dp"
         android:gravity="center_vertical"
         android:paddingLeft="10dp"
         android:text="test"
         android:textSize="20dip" />

 </LinearLayout>
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved