Cannot find view by ID when overlaying resources?

Viewed 396

I have a layout that contains a TextView that looks like this

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/visual_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor=?android:attr/colorAccent
        android:maxLines="3"
        android:gravity="center_vertical" />

I have specified an overlay directory and I'm attempting to overlay the layout file using a similar file except with some minor differences

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/visual_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor=?android:attr/colorPrimary
        android:maxLines="3"
        android:gravity="top" />

My application builds successfully, however, I'm seeing a NullPointerException during runtime when my Java code tries to set the text of the TextView

private void setVisualText(View someView) {
        View view = getLayoutInflater().inflate(R.layout.myLayout, someView, false);
        TextView myText = (TextView)view.findViewById(R.id.visual_text);
        myText.setText(R.string.myString);
}

The exception happens only with the overlay file and the code runs fine without the overlay. Does anyone know why myText is null and why it's not finding the view correctly? My guess is it's related to the ID but I'm not sure why it's not resolving correctly.

1 Answers

So you have a TextView and an overlaying TextView? If so, you should not use the same ids. Ids should be used only once.

Why are you calling?

getLayoutInflater().inflate(R.layout.myLayout, someView, false);

If you want to get a view from the main contentView, you can just use:

findViewById(id);

because if you want to attach the inflated view to the root you have to call:

getLayoutInflater().inflate(R.layout.myLayout, someView, true);

please try it with (..true). by using the line above, you are getting the contentView view.

Related