Reputation: 1415
I am including a layout in another like this:
<include
layout="@layout/_home"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
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.
Upvotes: 0
Views: 317
Reputation: 12886
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 CustomView.java
public class CustomView extends View {
private static final String TAG = "CustomViewTAG_";
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.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="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.example.CustomView>
<!-- Your normal views -->
</FrameLayout>
Upvotes: 1