Multiple layouts for the same Activity…

In the Apple world mobile apps have a one-to-one relationship between views and controllers. Apple uses the MVC or Model-View-Controller method of programming but there is only ever one view for any given controller. The Android world does not insist on the same thing. Views in the Android world are described by XML layout files which can be composed using a WYSIWYG designer or by putting together the raw XML.

So lets say that you have a state machine and you want to indicate to the user how the machine is progressing through the states. Each state change can present the user with options or my simply display a screen with information. Each of the screens then would be described by an XML layout file.

The state machine could be an initialization sequence at the start of the application. When the application starts it would display the first layout informing the user that the state machine has initialized and is either waiting for input or perhaps a network connection.

When the activity transitions to the next state it will load the next layout replacing the previous one. A method inside the activity might look like:

protected void showStateOne() {
setTitle(R.string.state_one);
setContentView(R.layout.activity_state_one);
}

When the program is ready to transition to state two it would call another activity like:

protected void showStateTwo() {
setTitle(R.string.state_two);
setContentView(R.layout.activity_state_two);
}

In this case there would be XML layout files called “activity_state_one.xml” and “activity_state_two.xml” that would contain messages, buttons and various other controls. There is no limit with respect to the number of views any one activity can have.

The code that monitors the state machine and changes the layouts could look like:

if (state.equals(myActivity.STATE_ONE)) {
showStateOne();
} else if (state.equals(myActivity.STATE_TWO)) {
showStateTwo();
} else {
Log.i(“StateMachine”,”unknown state”);
}

I’m not suggesting that it is generally a good idea to have multiple layouts for activities, but there are cases where is works really well and produces compact easy to understand code.

This entry was posted in General and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *