不能访问ViewStub'childViewStub、child

2023-09-06 22:07:00 作者:滥情嫌疑犯

我想使用VIEWSTUB合并内tag.and其工作well.I'm能够赶上 onclicklistenr ViewStub的父 button.But我想访问的按钮是viewstub内部。

I am trying to use VIEWSTUB inside the merge tag.and its working well.I'm able to catch onclicklistenr of ViewStub's parent button.But i want to access the button that is inside the viewstub.

1,主要的xml:

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

2.view存根布局                

2.view stub 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>

我夸大观点存根一个活动......在这里,我想火点击按钮事件cancel.How将有可能

I am inflating view stub in an activity...here i want to fire click event on button cancel.How it will be possible

推荐答案

让我们假设你的ViewStub ID是view_stub。你需要做的活动如下:

Let's suppose your ViewStub ID is view_stub. You need to do the following in the activity:

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

现在你可以做任何你想要的按钮:)也就是说,充气方法返回的存根布局,其中包含从XML文件中的实际内容。

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

当然,你总是可以有onClick的XML属性...

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

作为除去ViewStub - 问题是双重的(检查http://developer.android.com/resources/articles/layout-tricks-stubs.html):

As for removing the ViewStub - the question is two-fold (check http://developer.android.com/resources/articles/layout-tricks-stubs.html):

通胀ViewStub之前 - 你无法将其删除。有没有必要,不过,因为ViewStub没有尺寸,它不画任何东西,不参与任何形式的布局。

before inflation of the ViewStub - you cannot actually remove it. There's no need, though, since ViewStub "has no dimension, it does not draw anything and does not participate in the layout in any way".

通胀因素后 - 你只需要通过ViewStub.inflate()方法返回的视图,做任何你想做的事情 - 例如,隐藏

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