Zahema Zahema - 1 year ago 136
Android Question

How to set a java file for an included layout?

I am including a layout in another like this:


I want to create a java file with onCreate method that would fire when the layout is included anywhere.

I am new to android so I might be trying to do the wrong thing.

Answer Source

It would be kind of difficult, but, like @emanuel-moecklin mentioned, you can wrap your _home.xml layout with a custom view, and then you could do add some code in the onAttachedWindow, onMeasure, onLayout or onDraw methods, check out this image if you want to see more about the custom View lifecycle.

This would be your

public class CustomView extends View {

    private static final String TAG = "CustomViewTAG_";

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    protected void onAttachedToWindow() {
        Log.d(TAG, "This will get called everytime your CustomView gets attached");

And something like this would be your _home.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android=""



    <!-- Your normal views -->

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download