popstack
popstack

Reputation: 1787

web/android analogy: declarative vs programmatic layout

I have some web development experience and am learning how to build android apps.

I understand that XML layout allows a separation of program logic and (UI-) layout. This seems to be analogous to the separation of JavaScript from HTML/CSS.

But what plays the role of a server-side scripting language? i.e. if there is a list of audio files which the user could click on to play, how do I auto-generate the XML layout (which, in the web world, I would have done by interleaving HTML and PHP)? Or am I forced to do this programmatically?

Upvotes: 1

Views: 410

Answers (2)

Jeshurun
Jeshurun

Reputation: 23186

In the web programming world, since the client is physically separated from the server, there is a need for javascript for dynamic client interaction, and a server side language for processing the data. In the Android world, since both the view and the code are executing in the same device (like a desktop app), there isn't a need for scripting in the views. Because of this, xml layouts in Android are completely static layout definitions, like a simple HTML file. What happens when the user interacts with that layout will have to be defined in code in the Activity that is using this layout, which handles user events (javascript), and also processes them (server side language).

Using your example, if there are a list of audio files, and assuming you have used a spinner to allow the user to select one, you will have to attach an event handler using onClickListener or a variant, to tell the application what to do when the user selects it. If you use a ListView, you would usually extend ListActivity and then override onListItemClick() for the action to be performed when the user clicks it.

In the web programming world, this would be analogous to attaching a javascript event handler to an element on the page, which would then respond when the user performs an action, usually sending the data to the server for further processing.

So in short, yes, you will be forced to write code to respond to the user's actions, and you cannot interleave (script) code into the layout files.

The normal flow would be: 1. Define the layout in xml 2. use setContentView in onCreate in your Activity to indicate the layout you are using 3. Use the R object to get the elements defined in the layout by id using findViewById 4. Attach event handlers to these elements to respond when the user performs an action.

Upvotes: 2

Brayden
Brayden

Reputation: 519

Well for a list of audio files you'd probably want to use a ListView. You could declare the ListView in your XML layout, and then within your activity you get a handle on the ListView and set an adapter on it which fills it with your list of files. So it's a little bit of XML and programmatic layouts. You can always do both (add to your layout programmatically) if necessary.

Upvotes: 0

Related Questions