Android Combat Simple tutorial-60th gun (share a city Select function module)

Source: Internet
Author: User

In doing some of the app may use the function of the city selection module, this example can provide location self-positioning and manual selection of functions, very useful, you can modify and then join their own projects.

First look at the effect:

1. Access to some phones may prompt permission requirements, then we choose to allow.


2. Select Allow to enter:


This location can see that our city has been acquired by GPS


Click on this control and the city gets completed:


Let's take a look at how the key code is performing this function.

1.mainactivity.java:

Package Com.winxiang.locationselect;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.view.view;import Android.widget.textview;public class MainActivity extends Activity {private TextView city_name; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); city_name = (TextView) Findviewbyid (R.id.city_name);} public void Goselcet (View v) {startactivityforresult (new Intent (Mainactivity.this,activityselectcity.class), 99);} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub Try{switch (ResultCode) {case 99:city_name.settext (Data.getstringextra ("Lngcityname")); break;default:break;}} catch (Exception e) {e.printstacktrace ();} Super.onactivityresult (Requestcode, ResultCode, data);}}
Very simple, there is a jump button.

2.activityselectcity.java:

Package Com.winxiang.locationselect;import Java.util.arraylist;import Java.util.collections;import Java.util.comparator;import Java.util.hashmap;import Java.util.list;import Java.util.regex.pattern;import Org.json.jsonarray;import Org.json.jsonobject;import Com.baidu.location.bdlocation;import Com.baidu.location.bdlocationlistener;import Com.baidu.location.locationclient;import Com.baidu.location.locationclientoption;import Android.app.activity;import Android.app.progressdialog;import Android.content.context;import Android.content.intent;import Android.graphics.pixelformat;import Android.os.bundle;import Android.os.handler;import Android.text.editable;import Android.text.TextWatcher;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.view.viewgroup.layoutparams;import Android.view.windowmanager;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import AndroId.widget.baseadapter;import Android.widget.edittext;import Android.widget.imageview;import Android.widget.linearlayout;import Android.widget.listview;import Android.widget.textview;import Com.winxiang.locationselect.myletterlistview.ontouchingletterchangedlistener;public class ActivitySelectCity Extends Activity{private listadapter adapter;private ListView personlist;private ImageView imgback;private TextView Overlay dialog box initials textviewprivate Myletterlistview Letterlistview; A-Z listviewprivate hashmap<string, integer> alphaindexer;//Store existing initials and corresponding list location private string[] Sections ;//Store The presence of the first letter of the private Handler handler;private overlaythread overlaythread; Display the first letter dialog private arraylist<city> allcity_lists; List of all cities private arraylist<city> showcity_lists; List of cities to display-change private arraylist<city> city_lists;//City list with search private String lngcityname = "";//store returned city name private Jsonarray chinesecities;p rivate locationclient locationclient = null;private EditText sh;privateTextView lng_city;private linearlayout lng_city_lay;private progressdialog progress;private static final int SHOWDIALOG = 2;private static final int dismissdialog = 3; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (s Avedinstancestate); Setcontentview (r.layout.activity_selectcity);p ersonlist = (ListView) Findviewbyid (R.id.list_ view); allcity_lists = new arraylist<city> (); Letterlistview = (Myletterlistview) Findviewbyid ( R.ID.MYLETTERLISTVIEW01) Lng_city_lay = (linearlayout) Findviewbyid (r.id.lng_city_lay); sh = (EditText) findViewById ( r.id.sh); lng_city = (TextView) Findviewbyid (r.id.lng_city); imgback = (ImageView) Findviewbyid (r.id.imgback); Letterlistview.setontouchingletterchangedlistener (New Letterlistviewlistener ()); alphaindexer = new HashMap< String, Integer> (), Handler = new Handler (), Overlaythread = new Overlaythread ();p Ersonlist.setonitemclicklistener ( New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> arg0, View arg1, INT Arg2,long arg3) {Intent Intent = new Intent (); Intent.putextra ("Lngcityname", Showcity_lists.get (arg2). Name); Setresult (99,intent); Finish ();}); Lng_city_lay.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {Intent Intent = new Intent ( ); Intent.putextra ("Lngcityname", Lngcityname); Setresult (99,intent); Finish ();}); Imgback.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {finish ();}}); Initgps (); Initoverlay (); Handler2.sendemptymessage (SHOWDIALOG); Thread thread = new Thread () {@Overridepublic void run () {hotcityinit (); Handler2.sendemptymessage (DismissDialog); Super.run ();}}; Thread.Start ();}   /** * Popular cities */public void Hotcityinit ()  City = new City ("Shanghai", "" "), Allcity_lists.add (city), city = new City (" Beijing "," ""), Allcity_lists.add (city), city = new City ("Guangzhou", "Allcity_lists.add"); city = new City ("Shenzhen", "" "); Allcity_lists.add (city): City = new City (" Wuhan "," "); allcity_ Lists.add (city): City = new City ("Tianjin", "" "); allcity_lists.add (CITCity = new City ("Xian", "" "), Allcity_lists.add (city), city = new City (" Nanjing "," ""), Allcity_lists.add (city) and city = new City ("Hang State "," ""), Allcity_lists.add (city), city = new City ("Chengdu", "" "), Allcity_lists.add (city), city = new City (" Chongqing "," "); allcity_ Lists.add (city); city_lists = Getcitylist (); Allcity_lists.addall (city_lists); Showcity_lists=allcity_lists;} /** * * Get city list via JSON data * @author Yayun * @since September 18, 2015 * @return */private arraylist<city> getcitylist () {Arrayl ist<city> list = new arraylist<city> (); try {chinesecities = new Jsonarray (Getresources (). GetString ( R.string.citys)); for (int i=0;i<chinesecities.length (); i++) {Jsonobject jsonobject = Chinesecities.getjsonobject ( i); City City = new City (jsonobject.getstring ("name"), jsonobject.getstring ("pinyin")); List.add (city);}} catch (Exception e) {e.printstacktrace ();} Collections.sort (list, comparator); return list;} /** * A-Z sort */comparator Comparator = new comparator<city> () {@Overridepublic int compare (city LHS, city RHS){String a = Lhs.getpinyi (). substring (0, 1); String B = Rhs.getpinyi (). substring (0, 1), int flag = A.compareto (b), if (flag = = 0) {return A.compareto (b);} else {return F lag;}}};/ * * Adapter * of ListView * @author Yayun * @since September 18, 2015 * */public class ListAdapter extends Baseadapter {private Layout Inflater inflater;final int view_type = 3;public ListAdapter (context context) {This.inflater = Layoutinflater.from (  context); alphaindexer = new hashmap<string, integer> (); sections = new String[showcity_lists.size ()];for (int i = 0; I < showcity_lists.size (); i++) {//Current first letter String currentstr = Getalpha (Showcity_lists.get (i). Getpinyi ());//previous Hanyu Pinyin if not present as "" string Previewstr = (i-1) >= 0? Getalpha (Showcity_lists.get (i-1). Getpinyi ()): ""; if (!previewstr.equals (CURRENTSTR)) {String name = Getalpha ( Showcity_lists.get (i). Getpinyi ()); Alphaindexer.put (name, i); sections[i] = name;}} @Overridepublic int GetCount () {return showcity_lists.size ();} @Overridepublic Object getItem (int position) {return showcity_lists.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic int Getitemviewtype (int position) {//TODO auto-generated method Stubint type = 2;if (position = = 0&AMP;&A Mp;sh.gettext (). Length () ==0) {//Not in the search state type = 0;} return type;} @Overridepublic int Getviewtypecount () {//Here need to return the subscript that requires a centralized layout type, the total size of the seed number of the type, return view_type;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder Holder;int ViewType = Getitemvi Ewtype (position); if (Convertview = = null) {Convertview = inflater.inflate (R.layout.list_item, null); holder = new Viewholder (); holder.alpha = (TextView) Convertview.findviewbyid (r.id.alpha); holder.name = (TextView) Convertview.findviewbyid (R.id.name); Convertview.settag (holder);} else {holder = (Viewholder) Convertview.gettag ();} if (Sh.gettext (). Length () ==0) {//Search state//holder.name.settext (list.get (position). GetName ());// Holder.alpha.setVisibility (view.gone);//}else if (position>0) {//show Pinyin and popular cities, check the pinyin of this pinyin and the previous word one time, if the same does not show, if not the same show Holder.name.setText (Showcity_lists.get (position). GetName ()); String currentstr = Getalpha (showcity_lists.get (position). Getpinyi ());//This time pinyin string previewstr = (position-1) >= 0? Getalpha (Showcity_lists.get (position-1). Getpinyi ()): "";//previous Pinyin if (!previewstr.equals (CURRENTSTR)) {// Different displays holder.alpha.setVisibility (view.visible), if (Currentstr.equals ("#")) {currentstr = "hot City";} Holder.alpha.setText (CURRENTSTR);} else {holder.alpha.setVisibility (view.gone);} }return Convertview;} Private class Viewholder {TextView alpha;//first-letter title TextView name;//city name}}//initial initials popup box private void Initoverlay () {La Youtinflater Inflater = Layoutinflater.from (this); overlay = (TextView) inflater.inflate (r.layout.overlay, null); O Verlay.setvisibility (view.invisible); Windowmanager.layoutparams LP = new Windowmanager.layoutparams (layoutparams.wrap_content, LayoutParams.WRAP_CONTENT , windowmanager.layoutparams.type_application,windowmanager.layoutparams.flag_not_focusable| WinDowmanager.layoutparams.flag_not_touchable,pixelformat.translucent); WindowManager WindowManager = (windowmanager) this.getsystemservice (Context.window_service); WindowManager.addView ( overlay, LP);} Private class Letterlistviewlistener Implementsontouchingletterchangedlistener {@Overridepublic void Ontouchingletterchanged (final String s) {if (Alphaindexer.get (s)! = null) {int position = Alphaindexer.get (s);p ersonlist . setselection (position); Overlay.settext (Sections[position]); overlay.setvisibility (view.visible); Handler.removecallbacks (Overlaythread);//delay one second after execution, let overlay be invisible handler.postdelayed (Overlaythread, 1500);}} Set overlay invisible Private class Overlaythread implements Runnable {@Overridepublic void run () {overlay.setvisibility ( View.gone);}} Gets the initials private string Getalpha (String str) {if (Str.equals ("-")) {return "&";} if (str = = null) {return "#";} if (Str.trim (). Length () = = 0) {return "#";} char C = Str.trim (). substring (0, 1). charAt (0);//Regular expression to determine if the first letter is the English letter pattern = pattern.cOmpile ("^[a-za-z]+$"), if (Pattern.matcher (C + "). Matches ()) {return (C +" "). toUpperCase (); else {return ' # ';}} /** * * Initialize GPS * @author Yayun * @since September 18, 2015 */private void Initgps () {Try{mylocationlistenner MyListener = new MyL Ocationlistenner (); locationclient = new Locationclient (activityselectcity.this); Locationclient.registerlocationlistener (MyListener); locationclientoption option = new Locationclientoption (); Option.setopengps (true); Option.setaddrtype ("All"); O Ption.setcoortype ("Bd09ll"); Option.setscanspan (n); Option.disablecache (true); Option.setpoinumber (5); Option.setpoidistance (1000); Option.setpoiextrainfo (TRUE); Option.setpriority (Locationclientoption.gpsfirst); locationclient.setlocoption (option); Locationclient.start ();} catch (Exception e) {e.printstacktrace ();}} /** * Destroy */@Overridepublic void OnDestroy () {Super.ondestroy (); Locationclient.stop ();} /** * Get your current city via the Location SDK * @author Yayun * @since September 18, 2015 * */private class Mylocationlistenner implements Bdlocationliste Ner {@Overridepublic void onreceivelocation (bdlocation location) {if (location = = null) return; StringBuffer sb = new StringBuffer, if (location.getloctype () = = bdlocation.typegpslocation) {sb.append ( Location.getcity ());} else if (location.getloctype () = = bdlocation.typenetworklocation) {sb.append (location.getcity ());} if (sb.tostring () = null && sb.tostring (). Length () > 0) {lngcityname=sb.tostring (); Lng_city.settext ( lngcityname);}} public void Onreceivepoi (Bdlocation poilocation) {}}handler handler2 = new Handler () {public void Handlemessage ( Android.os.Message msg) {switch (msg.what) {Case showdialog:progress = apputil.showprogress (Activityselectcity.this, " Loading data, please wait ... "); Break;case dismissdialog:if (progress! = null) {Progress.dismiss ();} adapter = new ListAdapter (activityselectcity.this);p Ersonlist.setadapter (adapter);//personlist.setadapter (Adapter ); Sh.addtextchangedlistener (new Textwatcher () {@Overridepublic void ontextchanged (charsequence s, int start, int before , int CoUNT) {} @Overridepublic void beforetextchanged (charsequence s, int start, int count,int after) {} @Overridepublic void after TextChanged (Editable s) {//search for city names that match user input if (s.length () >0) {arraylist<city> changecity = new arraylist<city > (); for (int i=0;i<city_lists.size (); i++) {if (City_lists.get (i). Name.indexof (Sh.gettext (). toString ())!=-1) { Changecity.add (City_lists.get (i));}} showcity_lists = changecity;} else{showcity_lists = allcity_lists;} Adapter.notifydatasetchanged ();}}); Break;default:break;}};};}

3. Custom controls (Quick indexing):

Package Com.winxiang.locationselect;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.typeface;import Android.text.style.typefacespan;import Android.util.attributeset;import Android.view.motionevent;import Android.view.view;public class Myletterlistview extends View {Ontouchingletterchangedlistener Ontouchingletterchangedlistener; 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; Paint paint = new paint (); Boolean showbkg = False;public Myletterlistview (context context, AttributeSet attrs, int defstyl e) {Super (context, attrs, Defstyle);} Public Myletterlistview (context context, AttributeSet Attrs) {Super (context, attrs);} Public Myletterlistview (Context context) {super (context);} @Overrideprotected void OnDraw (canvas canvas) {Super.ondraw (canvas), if (showbkg) {Canvas.drawcolor (Color.Parsecolor ("#10000000"));}  int height = getheight (); int width = getwidth (); int singleheight = height/b.length;for (int i = 0; i < b.length; i++) {Paint.setcolor (Color.parsecolor ("#515151"));p Aint.settypeface (typeface.default_bold);p Aint.setantialias (True) if (i = = choose) {Paint.setcolor (Color.parsecolor ("#3399ff"));p Aint.setfakeboldtext (true);} float XPos = width/2-Paint.measuretext (B[i])/2;float YPos = singleheight * i + singleheight;canvas.drawtext (b[i], XP OS, YPos, paint);p aint.reset ();}} @Overridepublic 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_DOWN:showBkg = true;if (oldchoos E! = c && Listener! = null) {if (c >= 0 && C <= b.length) {listener.ontouchingletterchanged (b[c]); CH Oose = C;inValidate ();}} Break;case MotionEvent.ACTION_MOVE:if (Oldchoose! = c && Listener! = null) {if (c >= 0 && C <= b.len gth) {listener.ontouchingletterchanged (b[c]); choose = C;invalidate ();}} Break;case MotionEvent.ACTION_UP:showBkg = False;choose = -1;invalidate (); break;} return true;} @Overridepublic boolean ontouchevent (Motionevent event) {return super.ontouchevent (event);} public void Setontouchingletterchangedlistener (Ontouchingletterchangedlistener ontouchingletterchangedlistener) { This.ontouchingletterchangedlistener = Ontouchingletterchangedlistener;} Public interface Ontouchingletterchangedlistener {public void ontouchingletterchanged (String s);}


Run the effect:



In the space problem, other code you can download Source view:

SOURCE download

My favorite friends pay attention to me and my public number, thank you!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Combat Simple tutorial-60th gun (share a city Select function module)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.