UI update interaction mechanism and instance parsing of Android development

Source: Internet
Author: User

During Android development, it is often necessary to update the status and copywriting of the UI. This is where the UI needs to be updated. There are three ways to update the UI in Android, such as the handler mechanism, the Runonuithread method, and the Asynctask Async class method.

In this article, the following three methods are demonstrated and implemented in code.

The A.handler mechanism uses a message mechanism to implement

The B.runonuithread method is to achieve the purpose of updating the UI by running the UI thread

C.asynctask is an asynchronous class that updates the UI with an asynchronous update

As follows:

(1) Java function Implementation code is as follows:

 PackageCom.czm.updateui;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid. R.integer;Importandroid.app.Activity;ImportAndroid.graphics.Color;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView; Public classUpdateuiactivityextendsActivity {PrivateButton Btnhandler; PrivateButton Btnrunonuithread; PrivateButton Btnasynctask; PrivateTextView Tvhandler; PrivateTextView Tvonuithread; PrivateTextView tvprogress; PrivateHandler Uihandler; PrivateProgressBar ProgressBar; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.LAYOUT.UPDATE_UI);        Initviews ();    Setlisteners (); }    Private voidinitviews () {Btnhandler=(Button) Findviewbyid (R.id.btnhandler); Btnrunonuithread=(Button) Findviewbyid (R.id.btnrunonuithread); Btnasynctask=(Button) Findviewbyid (r.id.btnasynctask); Tvhandler=(TextView) Findviewbyid (R.ID.TVTEXT1); Tvonuithread=(TextView) Findviewbyid (R.ID.TVTEXT2); Tvprogress=(TextView) Findviewbyid (R.ID.TVTEXT3); ProgressBar=(ProgressBar) Findviewbyid (R.id.progressbar); }    Private voidsetlisteners () {Uihandler=NewHandler () {@Override Public voidhandlemessage (Message msg) {//TODO auto-generated Method Stub                Super. Handlemessage (msg); Bundle Bundle=Msg.getdata (); String text= Bundle.getstring ("Handler_text"); String Color= Bundle.getstring ("Handler_color");                Tvhandler.settext (text);                            Tvhandler.setbackgroundcolor (Color.Blue);        }                    }; //updating the UI with the handler mechanismBtnhandler.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method Stub                NewThread () {@Override Public voidrun () {//TODO auto-generated Method StubMessage msg =NewMessage (); Bundle Bundle=NewBundle (); Bundle.putstring ("Handler_text", "I am the copywriter after updating the UI by handler"); Bundle.putstring ("Handler_color", "#0000FF");                        Msg.setdata (bundle); //uihandler.sendmessagedelayed (msg, +);uihandler.sendmessage (msg);            }}.start ();                }        }); //to update the UI with RunonuithreadBtnrunonuithread.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubRunonuithread (NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method StubTvonuithread.settext ("I am a copywriter after updating the UI by Runonuithread");                                            Tvonuithread.setbackgroundcolor (color.red);            }                });        }        }); //to update the UI by Asynctask asynchronous TasksBtnasynctask.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method Stub                NewMyasynctask (). Execute (0);    }        }); }    Private classMyasynctaskextendsAsynctask<integer, Integer, integer>{@Overrideprotected voidOnPostExecute (Integer result) {//TODO auto-generated Method Stub            Super. OnPostExecute (Result); Tvprogress.settext ("Loading complete ... 100% "); } @Overrideprotected voidonprogressupdate (Integer ... values) {//TODO auto-generated Method Stub            Super. Onprogressupdate (values); Progressbar.setprogress ((int) (values[0])); Tvprogress.settext ("Loading ..." +values[0]+ "%"); } @Overrideprotectedinteger doinbackground (integer ... params) {//TODO auto-generated Method StubInteger Timer = 0;  while(Timer <=100){                Try{publishprogress (timer); Timer++; Thread.Sleep (40); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }            return NULL; }             }    }

(2) The corresponding UI layout XML file code:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"android:gravity= "Center_horizontal"Tools:context=". Updateuiactivity " >    <LinearLayoutAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:orientation= "Horizontal" >"        <ButtonAndroid:id= "@+id/btnhandler"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Handler" />    <ButtonAndroid:id= "@+id/btnrunonuithread"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Runonuithread" />    <ButtonAndroid:id= "@+id/btnasynctask"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Asynctask" />    </LinearLayout>        <TextViewAndroid:id= "@+id/tvtext1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_margintop= "10DP"Android:text= "Handler to update UI"android:padding= "3DP"Android:textcolor= "#FFF"Android:background= "#666666"android:textsize= "20DP" />    <TextViewAndroid:id= "@+id/tvtext2"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_margintop= "10DP"Android:text= "Runonuithread to update UI"android:padding= "3DP"Android:textcolor= "#FFF"Android:background= "#666666"android:textsize= "20DP" />        <ProgressBarAndroid:id= "@+id/progressbar"style= "? Android:attr/progressbarstylehorizontal"Android:layout_width= "Fill_parent"Android:layout_height= "25DP"android:progressdrawable= "@drawable/progressbar"Android:max= "+"android:progress= "0"Android:layout_marginleft= "5DP"Android:layout_marginright= "5DP"Android:layout_margintop= "10DP"         />    <TextViewAndroid:id= "@+id/tvtext3"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Ready to load ... 0% "android:textsize= "20DP" />        </LinearLayout>

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.