chrismacpherson.com

Home

Latest Post...

Dynamic Content and Compound Views

date

A problem I have just overcome with my current project, an Android App, is how to create dynamic content. Not only this but I wanted to create a Compound Control, which is built up of multiple child Views, with which I could repeatedly insert into my layout.

After some research I discovered how to create a Compound Control programmatically, instantiating Views and adding them to a Layout.

For example the following creates a new LinearLayout and adds a TextView to it.

LinearLayout mTimeLayout = new LinearLayout(context);
mTimeLayout.setOrientation(HORIZONTAL);
            
mTime = new TextView(context);
mTime.setText(String.valueOf(hours) + ":" + String.valueOf(minutes));
mTimeLayout.addView(mTime, new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

This works well, but the code can get a bit unwieldy if you have many Views with corresponding settings to configure. A much simpler and more elegant solution is to use XML layout files and inflate them at run time.

This also enables you to design the look of the layout using the IDE, dragging and dropping Views in at will.

To do this create a new .xml file in the /res/layout directory and open it up. Then hit the 'Layout' tab to see how your Layout looks and to add and remove Views.

Now in your code you can get the inflated structure by calling the following code:

View compoundControl = null;
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
compoundControl = inflater.inflate(R.layout.yourlayoutname, null);

// Set the text of a TextView contained within the compound control
TextView txtName = (TextView) compoundControl.findViewById(R.id.name);
txtName.setText(String.valueOf("Chris"));