Android programming weather forecast down Refresh data and City container configuration--3

Source: Internet
Author: User
Tags gety

In front of the activities and services have been told, to pay attention to the use of services, we are here is extends Intentservice implements Locationlistener, below to see Intentservice


Intentservice is a service that starts by Context.startservice (Intent) that can handle an asynchronous request, and when used you only need to inherit Intentservice and override the Onhandleintent ( Intent) method receives a Intent object and stops itself at the appropriate time (usually when the job is completed). All requests are processed in a single worker thread, which alternately executes (but does not block the execution of the main thread), can only execute one request at a time, Message Queuing mode This is a message-based service, and each time the service is started it does not immediately process your work, but first creates the corresponding looper. Handler and the message object that accompanies the customer Intent added in MessageQueue, and then gets the Intent object when Looper finds a message in Onhandleintent ((Intent) Msg.obj) Call your handler. After processing, you will stop your service. Meaning that the life cycle of intent is consistent with the task you are dealing with. So this class is very good with the download task, and the service itself ends the exit after the download task finishes.Intentservice uses the queue to join the requested intent to the queue, then opens a worker thread to handle intent in the queue, and for asynchronous StartService requests, Intentservice will process the completion of a second after processing, each request will be processed in a separate worker thread, will not block the application's main thread, here gives us a thought, It is better to use Intentservice to handle time-consuming operations if there is a time-consuming operation than opening a new thread within the service
Talk about it today. Refresh and City container management, a lot about the ListView content will usually use down to refresh and pull up load more operations, such as QQ mobile phone side of the message list, pull down can refresh the message list, the city container, For the time being, we just wrote a ArrayList. Define a set of existing city data, later need to consider using XML to access data, including some weather information can be stored, that is, in the case of poor network conditions, so that our app can use local data, the interface will not appear so empty , XML access, sharedpreferences for some account information or other small data access
City container, add City dialog:
   
Package com.newer.myweather;/** * City container, City Add Dialog * @author engineer-jsp * @date 2014.10.27 * */import java.util.ArrayList ; Import Android.app.activity;import Android.app.alertdialog;import Android.app.alertdialog.builder;import Android.content.dialoginterface;import Android.content.dialoginterface.onclicklistener;import Android.os.Bundle; Import Android.view.actionmode;import android.view.menu;import android.view.menuitem;import Android.view.View; Import Android.widget.abslistview.multichoicemodelistener;import Android.widget.arrayadapter;import Android.widget.edittext;import Android.widget.listview;public class Locationactivity extends Activity Implementsmultichoicemodelistener {Private ListView locationlistview;private arrayadapter<string> adapter; Private EditText edittext;private long mposition; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.location); MainActivity.locations.clear (); MainActivity.locations.add ("Long  Sand "); MainActivity.locations.add ("Shenzhen"); MainActivity.locations.add ("Yueyang"); MainActivity.locations.add ("Changde"); Locationlistview = (ListView) Findviewbyid (r.id.locations); adapter = new Arrayadapter<string> (This,r.layout.city_item,r.id.city_item_content, mainactivity.locations); Locationlistview.setadapter (adapter); adapter.notifydatasetchanged (); Locationlistview.setchoicemode ( Listview.choice_mode_multiple_modal); Locationlistview.setmultichoicemodelistener (this);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (r.menu.location, menu); return Super.oncreateoptionsmenu (menu);} @Overridepublic boolean onoptionsitemselected (MenuItem item) {if (item.getitemid () = = R.id.ic_action_add) { Showadddialog ();} return super.onoptionsitemselected (item);} private void Showadddialog () {editText = new EditText (this); Edittext.sethint ("Please enter Address"); Edittext.setsingleline (true); Alertdialog.builder builder = new Builder (this). Settitle ("add Address"). Setview (EditText). Setnegativebutton ("Cancel", null). Setpositivebutton (" OK ", new Onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {String input = Edittext.gettext (). toString (). Trim (); MainActivity.locations.add (input);}}); Builder.show ();} @Overridepublic boolean Oncreateactionmode (Actionmode mode, menu menu) {getmenuinflater (). Inflate (R.menu.location, menu); Mode.settitle ("select"); return true;} @Overridepublic boolean Onprepareactionmode (Actionmode mode, menu menu) {return false;} @Overridepublic boolean onactionitemclicked (actionmode mode, MenuItem Item) {if (item.getitemid () = = R.id.ic_action_ Delete) {///mainactivity.locations.remove (mposition);} return false;} @Overridepublic void Ondestroyactionmode (Actionmode mode) {} @Overridepublic void onitemcheckedstatechanged ( Actionmode mode, int position,long ID, Boolean checked) {mposition = Id;int count = Locationlistview.getcheckeditemcount () ; Mode.setsubtitle (Count + "item");}}

Drop-down refresh:
Package com.newer.myweather.weight;/** * Drop-down Refresh data * @author engineer-jsp * @date 2014.10.27 * */import java.util.date;import Com.newer.myweather.r;import Android.content.context;import Android.util.attributeset;import Android.view.layoutinflater;import Android.view.motionevent;import Android.view.view;import Android.view.viewgroup;import Android.view.animation.animation;import Android.view.animation.LinearInterpolator; Import Android.view.animation.rotateanimation;import Android.widget.abslistview;import Android.widget.ImageView; Import Android.widget.listadapter;import Android.widget.listview;import Android.widget.abslistview.onscrolllistener;import Android.widget.progressbar;import Android.widget.TextView; public class Mylistview extends ListView implements Onscrolllistener {private View headview;private ImageView Arror;priva Te ProgressBar progressbar;private TextView title;private TextView last_update;private int headcontentwidth;private int headcontentheight;private int Firstvisableindex;//the first place in the page to see the item (ListView) Private Animation animation;private Animation animation2;private float starty;// Used to record when the Headeview is about to be displayed, the position is recorded only once in the entire slide, private Boolean isrecord = false;  Used to record whether Starty has recorded private float tempy;//dynamic y-axis coordinates private final static int pull_to_refresh = 0;//drop-down refresh private final static int Release_to_refresh = 1;//Release Refresh private final static int refreshing = 2;//refreshing private final static int done = 3;//Refresh complete privat e int state;//Current drop-down refreshes the status of the control private Boolean isback= false;//records whether to refresh private onrefreshlistener from the release refresh back to the dropdown refreshlistener;// Refresh Listener Private final static int RATIO = 3;//The actual pull distance and Headview distance from the top of the page//300px100px;public Mylistview (context context) { Super (context); init (context);} Public Mylistview (context context, AttributeSet Attrs) {Super (context, attrs); init (context);} private void init (context context) {///1: The header is synthesized with the listview//layoutinflater Inflater = Layoutinflater.from (context);// Inflater.inflate (Resource, Root, attachtoroot); Headview = view.inflate (Context, R.layout.heaDer, null); Arror = (ImageView) Headview.findviewbyid (r.id.arror);p Rogressbar = (progressBar) Headview.findviewbyid ( R.id.progressbar); title = (TextView) Headview.findviewbyid (r.id.title); last_update = (TextView) Headview.findviewbyid (r.id.last_update); arror.setminimumwidth; Arror.setminimumheight (50);// Measure the size of the header control Measureview (Headview),//Get Haderview measurement after the size headcontentwidth = Headview.getmeasuredwidth (); Headcontentheight = Headview.getmeasuredheight ();//Specify Headview position headview.setpadding (0,-1 * headcontentheight, 0, 0); /Bind Addheaderview (Headview);//listview add Onscrolllistenersetonscrolllistener (this);//create arrows to use animation//Right → left animation = new Rotateanimation (0, -180, animation.relative_to_self, 0.5f, Animation.relative_to_self, 0.5f); Animation.setduration ( Animation.setfillafter (True); Animation.setinterpolator (new Linearinterpolator ());//Modify Animation Run effect/** * Interpolator defines the speed of the animation, which can achieve constant velocity, positive acceleration, negative acceleration, irregular acceleration, etc. acceleratedecelerateinterpolator, delay deceleration, when the action is performed in the middle of the time to perform the effect. Accelerateinterpolator, will make the parameter slowly to (float)Reduce speed. Linearinterpolator, steady decelerateinterpolator, accelerating in the middle, two slow cycleinterpolator, curved motion effects, to pass the float type parameters. * *///Left → right animation2 = new Rotateanimation ( -180, 0, Animation.relative_to_self, 0.5f, Animation.relative_to_self, 0.5f); Animation2.setduration (+); Animation2.setfillafter (true); Animation2.setinterpolator (new Linearinterpolator ()) ;//Modify animation Run effect}//measure the size of the header control private void Measureview (View child) {//child <==> headviewviewgroup.layoutparams LP = Child.getlayoutparams ();//initialization operation if (LP = = NULL) {LP = new Viewgroup.layoutparams (ViewGroup.LayoutParams.FILL_PARENT , ViewGroup.LayoutParams.WRAP_CONTENT);} Set control dimensions int childwidth = viewgroup.getchildmeasurespec (0, 0, lp.width); int childheight;if (lp.height > 0) {// Headview has its own height childheight = Measurespec.makemeasurespec (Lp.height, measurespec.exactly);} else {//headview is not height specified as 0childHeight = Measurespec.makemeasurespec (0, measurespec.unspecified);} Record the size of the control after measurement child.measure (childwidth, childheight);} @Overridepublic void Onscroll (Abslistview arg0, int firstvisableitem, int arg2, int arg3) {//TODO auto-generated method Stub//firstvisableitem The first one in the page to see item (Listvie W) Position firstvisableindex = Firstvisableitem;} @Overridepublic void onscrollstatechanged (Abslistview arg0, int arg1) {//TODO auto-generated method stub}@ Overridepublic boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case motionevent.action_down://pressed If the current first seen item is 0 position at the same time Starty is not recorded, this time record startyif (Firstvisableindex = = 0 &&!isrecord) {starty = Event.gety ( ); IsRecord = true;//fix record starty point status}break;case motionevent.action_move://move tempy = Event.gety (); if (Firstvisableindex = = 0 &&!isrecord) {starty = Tempy;isrecord = true;} In the non-sliding state, the slide effect of the ListView is if (state = refreshing) {///drop-down Refresh status if (Pull_to_refresh = =) {setselection (0); if (Tempy- Starty) <= 0) {//drop-down refresh status push up to hide the entire headview back to the refresh complete state = Done;//headview Control status change Changeheadviewofstate ();} else if ((t  Empy-starty)/ratio > Headcontentheight) {//drop-down refresh status pull down to show the entire HeadviewCame loose refresh state = Release_to_refresh;//headview Control status change Changeheadviewofstate ();}} Release the Refresh status if (state = = Release_to_refresh) {setselection (0), if ((Tempy-starty) <= 0) {//drop-down refresh status push up to hide the whole headview back to the brush New completion state = Done;//headview Control status change Changeheadviewofstate ();} else if ((tempy-starty)/ratio < headcontentheight && (Tempy-starty) > 0) {//Release refresh status push up to hide part of Headview The display part comes down to the drop-down refresh state = Pull_to_refresh;isback = true;//Release Refresh--drop-down refresh//headview control status Change Changeheadviewofstate ();}} Refresh completion Status if (state = = do) {if ((Tempy-starty) > 0) {//Refresh complete drop-down entered drop-down refresh state = Pull_to_refresh;//headview control state Changes change Headviewofstate ();}}} setpadding (int left, int top, int. right, int bottom) headview.setpadding (0, (int) ((tempy-starty)/ratio-headcontenthei Ght), 0, 0); Break;case motionevent.action_up://Let if (state = = Pull_to_refresh) {//Go back to the refresh-complete status: Changeheadviewofstate ();} if (state = = Release_to_refresh) {//go into the refresh status of the states = Refreshing;changeheadviewofstate ();//Data Refresh Onrefresh ();} break;} InvalidAte ();//listview Redraw return True;//return super.ontouchevent (event);} Headview Control status Change private void Changeheadviewofstate () {switch (state) {Case pull_to_refresh://drop-down refresh arror.setvisibility (view.visible);p rogressbar.setvisibility (View.gone); title.setvisibility (view.visible); last_ Update.setvisibility (view.visible); Title.settext ("drop-down Refresh");//Specify Animation arror.clearanimation (); if (isback) {//release refresh-- Drop-down refresh//left-to-right pointer arror.startanimation (animation2); isback = false;} Break;case release_to_refresh://Release Refresh arror.setvisibility (view.visible);p rogressbar.setvisibility (View.GONE); Title.setvisibility (view.visible); last_update.setvisibility (view.visible); Title.settext ("Release Refresh"); Arror.clearanimation ();//Right-to-left counterclockwise arror.startanimation (animation); Break;case refreshing:// Refreshing arror.setvisibility (view.gone);p rogressbar.setvisibility (view.visible); title.setvisibility (View.VISIBLE); Last_update.setvisibility (view.visible); Title.settext ("refreshing ...");//setpadding (int left, int top, int. right, int Bottom) headview.setpadding (0,0, 0, 0); Break;case done://Refresh complete arror.setvisibility (view.visible);p rogressbar.setvisibility (View.gone); Title.setvisibility (view.visible); last_update.setvisibility (view.visible); Title.settext ("drop-down refresh"); Headview.setpadding (0,-1 * headcontentheight, 0, 0); break;}} Refresh Data private void Onrefresh () {Refreshlistener.onrefresh ();} Provide access interface public interface onrefreshlistener{abstract void Onrefresh ();} public void Setonrefreshlistener (Onrefreshlistener listener) {Refreshlistener = listener;} Operation update Time after refresh, update headview status public void Onrefreshcomplete () {//update headview status state = Done;changeheadviewofstate ();// Update Time Last_update.settext ("Update to:" + new Date (). toLocaleString ());} @Overridepublic void Setadapter (ListAdapter adapter) {Super.setadapter (adapter);//Update Time Last_update.settext ("Update to:" + New Date (). toLocaleString ());}}

Drop-down refresh:
To release the refresh:
Refresh complete, update data:
The data will be refreshed to the official data, and if there is no official update, the list will be the same as before the refresh, as the data comes from the official

Android programming weather forecast down Refresh data and City container configuration--3

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.