Janko92 :
So I've this custom layout.
public class MyCustomView extends ConstraintLayout {
private Button myFancyButton;
public MyCustomView (@NonNull Context context, AttributeSet attrs) {
super(context,attrs);
myFancyButton = findViewById(R.id.button); //THIS IS NULL
}
public void init(){
myFancyButton = findViewById(R.id.button); //WORKS GREAT
}
}
The problem is I would rather not create a function "init" to do the work that is suited for a constructor. The issue I'm facing is calling findViewById in the constructor causes it to be null. Using the init function on a MyCustomView object works just fine. But I much rather do this in the constructor.
The corresponding XML file looks as follows.
<?xml version="1.0" encoding="utf-8"?>
<se.test.test.test.MyCustomView xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<Button
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="B1"
android:textSize="30sp"/>
</se.test.test.test.MyCustomView>
Froyo :
You need to put that code in onFinishInflate()
- That method is called when the layout and its children are inflated.
@Override
public void onFinishInflate() {
myFancyButton = findViewById(R.id.button)
}
https://developer.android.com/reference/android/view/View#onFinishInflate()