LinearLayout(带有onClick)包含ImageButton - 有更好的方法来解决它吗?
目前我有类似的东西:
<LinearLayout android:layout_height="80dip" android:id="@+id/linearLayoutSettings"
android:layout_width="80dip" android:orientation="vertical">
<ImageButton android:layout_height="wrap_content" android:src="@android:drawable/ic_menu_manage"
android:id="@+id/imageButton1" android:layout_width="wrap_content"></ImageButton>
</LinearLayout>
LinearLayout 附加了 onClick 侦听器。
问题:当在 LinearLayout 内单击 ImageButton 时,不会触发该事件。
我可以通过将与附加到 LinearLayout 相同的单击附加到此按钮来解决它。但在这种情况下,这将意味着大量重复代码(有很多按钮)。
问题:有没有更有效的方法来解决这个问题?
At the moment I have something like that:
<LinearLayout android:layout_height="80dip" android:id="@+id/linearLayoutSettings"
android:layout_width="80dip" android:orientation="vertical">
<ImageButton android:layout_height="wrap_content" android:src="@android:drawable/ic_menu_manage"
android:id="@+id/imageButton1" android:layout_width="wrap_content"></ImageButton>
</LinearLayout>
LinearLayout has onClick listener attached to it.
Problem: When a ImageButton is clicked inside the LinearLayout, the event doesn't get triggered.
I could solve it by attaching the same on click to this button as I attached to LinearLayout. But in that case it would mean a lot of repetetive code (have many buttons).
Question: Is there a more effective way to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将 ImageButton 更改为 ImageView,您将开始获取单击事件
Change the ImageButton to an ImageView and you will start getting the click event
将以下标签附加到每个图像按钮:
android:onClick="yourOnClickFunction"
然后,在您的活动中添加相应的功能:
在开关块中,您需要了解按钮 ID。您可以通过 findViewById(R.id.aButton) 获取它们。
Attach the following tag to each imagebutton:
android:onClick="yourOnClickFunction"
Then, in your activity, add a corresponding function:
In the switch-block you need to know about the buttons IDs. You can get them via findViewById(R.id.aButton).
您可以编写循环来查找布局中的所有按钮,并将创建的侦听器附加到所有按钮。
You can write loop finding all buttons in layout and attach once created listener to all of them.
如果我理解正确,当单击按钮时,LinearLayout 的 onClickListener 不会触发。这是有道理的。
您可以做的是放置一个
yourLinearLayout.performClick();
,它将以编程方式触发布局 onClick 事件。如果您将其放在 onClick 按钮的末尾,那么它将按顺序执行按钮,然后是布局。If I understand correctly, when the button is clicked, the LinearLayout's
onClickListener
doesn't fire. Which makes sense.What you can do is put a
yourLinearLayout.performClick();
which will programatically fire the layouts onClick event. If you put it at the end of the buttons onClick then it will perform the buttons, then the layouts, in order.您必须设置属性
setClickable(true);
!!您可以使用
android:clickable="true"
在 xml 中访问它you must set the attribute
setClickable(true);
!!you can access it in xml using
android:clickable="true"