Search This Blog

Tuesday 29 May 2012

How to update a UI in an Android Activity

The activity creates the UI View on the OnCreate method.

  /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

In this function you can set your view using the setContentView API.

setContentView API sets an explicit view to the UI.

Now you can update the UI by implementing a simple handler.

final Handler mHandler = new Handler()
     {
          public void handleMessage(Message msg)
          {
                  if(msg.what == 1)
                        textview.setText(msg.obj.toString());
                  else
                        textview.setText("Default Message");
          }
}

Now you can send the message to the handler to update the UI elements

   Message msg = Message.obtain(mHandler);
  msg.what = 1;  
  msg.obj = "Hello";
  mHandler.sendMessage(msg);

msg.what is used to define what type of message you are sending so you can implement the handler function for that message.

When a process is created for application, its main thread is dedicated to running a message queue that takes care of managing the all activities and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler.

This can be done by posting or sending a message to the message queue. The message is picked by message queue and the action will be taken as implemented in handler function. 



No comments:

Post a Comment