Failed to access ViewStub'child

I am trying to use VIEWSTUB inside a merge tag and its working capacity. I can catch onclicklistenr from parent button of ViewStub . But I want to access the button that is inside the viewstub.

1.Main xml:

<merge> <LinearLayout> <Button></Button> <ViewStub></ViewStub> </LinearLayout> </merge> 

2.view layout layout

 <Button android:id="@+id/button_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="100dip" android:text="Next" /> <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/imageView" android:background="@drawable/golden_gate" /> </LinearLayout> 

I am inflating the viewing of the stub in activity ... here I want to fire the click event on the cancel button. How will this be possible

+6
source share
1 answer

Suppose your ViewStub ID is view_stub. You need to do the following:

 ViewStub viewStub = (ViewStub) findViewById(R.id.view_stub); View inflatedView = viewStub.inflate(); Button button = (Button) inflatedView.findViewById(R.id.button_cancel); 

Now you can do whatever you want with the button :) That is, the inflate method returns a stub layout that contains the actual elements from the XML file.

Of course, you can always have the onClick XML attribute ...

How to remove ViewStub is a double question (check http://developer.android.com/resources/articles/layout-tricks-stubs.html ):

  • before inflation ViewStub - you actually cannot delete it. It is not necessary, however, since the ViewStub "has no dimension, it does not draw anything or participate in the layout in any way."

  • after inflation - you just take the View returned by the ViewStub.inflate () method and do whatever you want, for example, hide it.

+20
source

Source: https://habr.com/ru/post/887896/


All Articles