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

0 Comments

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.

1.public class SettingsScreenLayout extends LinearLayout {
2.  public SettingsScreenLayout(Context context) {
3.    super(context);
4. 
5.    LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
6.    layoutInflater.inflate(R.layout.settings, this);
7.  }
8.}

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