Craig Gidney
Craig Gidney

Reputation: 18276

Android findViewById returns null, but only for my custom view

I have an activity with a button on it:

<Button
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_alignParentTop="true"
    android:id="@+id/some_id" />

and I can find it just fine from the activity's source:

button = (Button)findViewById(R.id.some_id); // returns the button

but if I switch the button for a custom control:

<FancyButton
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_alignParentTop="true"
    android:id="@+id/some_id" />

then I start getting null instead:

fancyButton = (FancyButton)findViewById(R.id.some_id); // returns null

Fancy button is really just an empty view at the moment, so I'm not sure what could cause it to fail like this:

public FancyButton(Context context, AttributeSet attrs) {
    super(context);

    LayoutInflater.from(context).inflate(R.layout.fancy_button, this, true);
}

I definitely missed something obvious.

Upvotes: 0

Views: 75

Answers (1)

Craig Gidney
Craig Gidney

Reputation: 18276

I forgot to forward the attributes parameter to the base constructor. Since the id is an attribute, it ended up dropped on the floor instead of set.

Wrong:

public FancyButton(Context context, AttributeSet attrs) {
    super(context);

Right:

public FancyButton(Context context, AttributeSet attrs) {
    super(context, attrs);

Turning on "unused parameter" warnings would have caught this faster.

Upvotes: 1

Related Questions