I use the following technique:
<!-- content.xml -->
<merge>
<ImageView android:id="@+id/image />
<Button android:id="@+id/button />
<TextView android:id="@+id/text />
</merge>
Then inflate using a LayoutInflater:
View block = inflater.inflate(R.layout.content, root, attach);
(TextView) textView = (TextView) block.findViewById(R.id.text);
textView.setText(text);
I found this especially useful when you write a custom View extending a ViewGroup (eg LinearLayout or RelativeLayout) and you want to define the content in a declarative XML. For example
public class MyWidget extends LinearLayout {
// Invoked by all of the constructors
private void setup() {
Context ctx = getContext();
inflate(ctx, R.layout.content, this);
((TextView) findViewById(R.id.text)).setText(
ctx.getString(R.string.hello_world)
);
}
}
A possible variation is using a Layout instead of <merge> if you don't need it. The LayoutInflater can be obtained by Activity.getLayoutInflater() or by any Context via getSystemService() (you have to cast the result to a LayoutInflater object in the latter case.