Android: How to load an XML layout onto your layout instead of Activity

For Android activities, they have a very hand function called setContentView() which accepts the layout ID as a parameter.

I found myself having to use a layout instead of an activity to create a settings screen, but layouts aren't fortunate as activities to have a helper function. Luckily, it doesn't make it much harder to do so!

When defining your layout, simply use the following 2 magic lines to get layout XML to inflate onto your layout.

public class SettingsScreenLayout extends LinearLayout {
public SettingsScreenLayout(Context context) {

LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.settings, this);

The LayoutInflater will automatically unpack the XML file and place the objects onto your layout.

[ Source ]

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog