BrainCrash
BrainCrash

Reputation: 13172

Get reference of custom view by id declared in xml from activity

I have a custom view that extends ImageView and I use it in an XML layout like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp">

        <com.android.example.MyView
            android:id="@+id/myview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />

        <com.android.example.MyView
            android:id="@+id/myview2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />

    </LinearLayout>

</LinearLayout>

in my activity I do the usual: setContentView(R.layout.myLayout) .

Now, I need to get the reference of my class/View "MyView" in order to set a custom listener, but I i'm not able to get it from the id.

myview (MyView) findViewById(R.id.myview1);

returns null.

I tried to look at similar issues but haven't found any that helped me.

Please, note that if I add the View to the layout programmatically from the Activity everything is working fine, but I would like to be able to find what the issue is here.

Thanks in advance.

Upvotes: 1

Views: 1723

Answers (2)

BrainCrash
BrainCrash

Reputation: 13172

I found the issue was a stupid cut and paste mistake where I forgot to add the AttributeSet when calling the super()

having

public MyView(Context context, AttributeSet attrs) {
    super(context);
}

instead of

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

Upvotes: 1

Blundell
Blundell

Reputation: 76458

It does work.

The layout you're using for setContentView must be the same layout you have added your custom view to.

Upvotes: 1

Related Questions