MasterofProject

Handler small example, the replacement button background color

Classification: Android finishing 180 people read Comment(0) Collection Report

In the past few days has been busy in the development of a new project, write code written in pitch darkness, smoke today a few minutes to write a very simple example, another day will have the time to write!

Layout file is very simple, just a Button:

Xmlns:android= http://schemas.android.com/apk/res/android "<RelativeLayout"
Http://schemas.android.com/tools "xmlns:tools="
@+id/LinearLayout1 "android:id="
Match_parent "android:layout_width="
Match_parent "android:layout_height="
Android:orientation= "vertical" >

<Button
@+id/handler_btn "android:id="
Match_parent "android:layout_width="
Wrap_content "android:layout_height="
Android:text= "ColorButton" / >

</RelativeLayout>

Master interface code, a detailed notes:
Class MainActivity extends Activity public {
* / / * * button
Button BTN private;
Update UI main thread object * / / * *
Handler handler new = Handler private () {
Asynchronous receive messages * / / * *
@Override
Void handleMessage public (MSG Message) {
Super.handleMessage (MSG);
Get data from Map / * * * /
Bundle Bundle = msg.getData ();
Get the color value * / / * *
Color int = bundle.getInt ("color");
MainActivity.this.btn.setBackgroundColor (color); / / update the background color of the button
}


};


@Override
Void onCreate public (savedInstanceState Bundle) {
Super.onCreate (savedInstanceState);
SetContentView (R.layout.activity_main);
This.btn = (Button) findViewById (R.id.handler_btn);
Btn.setOnClickListener (btnOnClickListener new);
}


BtnOnClickListener implements OnClickListener class {
Void onClick public (V View) {
My new = MyThread MyThread ();
Start the thread * / / * *
Thread new (my).Start ();
}
};


MyThread implements Runnable class {


Void run public () {
{try
Thread.sleep (3000); / / Zi Xiancheng sleep for 3 seconds
} catch (E InterruptedException) {
E.printStackTrace ();
}
* / / * * message
MSG new = Message Message ();
Bundle new = Bundle Bundle ();
Bundle.putInt ("color", Color.RED);
Msg.setData (bundle);
/ * * send message, notify the main thread update * /
MainActivity.this.handler.sendMessage (MSG);
}
};
}

Copyright statement: This article is the original article of the main Bo, without the permission of the owner.

Top
0
Step
0
Guess what you're looking for.
View comments
* above the user's comments only represent their personal views, do not represent the views or position of the CSDN website
    Personal data
    • Visit36187 times
    • Integral:1741
    • Grade
    • Rank:13023rd
    • Original144
    • Reprint:36
    • Translation:1
    • Comment:9
    Latest comments