Aaron Flores
Aaron Flores

Reputation: 81

Android Studio: findViewId not working with custom views

I've read all the other questions relating to this, and most answers refer to all views, and the issue is usually with all views, but if I call findviewbyid for a built in view in the same place in code, it returns the view, but if I call it for a custom view, it just returns null. Both views are in the same place, in the same layout, have ID's, they are carbon copies inside the layout xml file. I correctly overridden all the constructors for the customView calling super(...) in each one. I am calling findViewById AFTER setContentView, and inside the Activity Class.

My question is, besides overriding the constructors, what else needs to be done to a custom view to allow it to be found by the function findViewByID? There has to be something missing.

protected void initClickCounter() {
    numberClicks = new DigitViewGroup(this);
    ImageDigitView v1;
    ImageView v2;

    v1 = (ImageDigitView) findViewById(R.id.imageViewDigit1);
    v2 = (ImageView) findViewById(R.id.imageViewDigit1_2);

v1 is always null, while v2 is never null.

<com.bilowik.debugg.ImageDigitView
    android:id="@+id/imageViewDigit1"
    android:layout_width="10dp"
    android:layout_height="14dp"
    android:layout_gravity="bottom"
    android:layout_marginBottom="60dp"
    android:layout_marginStart="103dp"
    android:contentDescription="@string/digit1"
    app:srcCompat="@drawable/digit_0" />

<ImageView
    android:id="@+id/imageViewDigit1_2"
    android:layout_width="10dp"
    android:layout_height="14dp"
    android:layout_gravity="bottom"
    android:layout_marginBottom="60dp"
    android:layout_marginStart="103dp"
    android:contentDescription="@string/digit1"
    app:srcCompat="@drawable/digit_0" />

They are identical besides the IDs.

public ImageDigitView(Context context) {
    super(context);
    init(context);
}

public ImageDigitView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    init(context);
}

public ImageDigitView(Context context, AttributeSet attributeSet, int  defStyle) {
    super(context, attributeSet, defStyle);
    init(context);
}

The constructors for the ImageDigitView class.

Upvotes: 2

Views: 944

Answers (2)

Trinadh Koya
Trinadh Koya

Reputation: 1087

get the rootView of your layout ,from that you can work out. In Fragment:

    View rootView = inflater.inflate(R.layout.some_x_layout, container, false);
    TextView tv = (TextView)rootView.findViewById(R.id.tv);

Upvotes: 0

Catarina Ferreira
Catarina Ferreira

Reputation: 1854

Use something like this example:

View yourviewname = inflater.inflate(R.layout.yourlayout, container, false);
Button expandableButton = (Button)yourviewname.findViewById(R.id.expandableButton1);

Upvotes: 1

Related Questions