我有一个 ImageButton 和一个包裹该按钮的 LinearLayout,如下所示:
<LinearLayout
android:id="@+id/homeButtonLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/p_buttons_background"
android:orientation="vertical" >
<ImageButton
android:id="@+id/homeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:background="@drawable/home_icon"
android:onClick="goBackToCameraScreen" />
</LinearLayout>
我在 ImageButton 周围放置了背景在线性布局中,如您在上面所看到的。
我希望能够改变那个背景(也就是说,LinearLayout 的背景,而不是 ImageButton 的背景)当用户单击 ImageButton 时。我可以通过编程方式做到这一点,但我想通过 XML 做到这一点。我可以轻松更改背景图像按钮的通过编写一个选择器,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>
That's EXACTLY我想要什么,除了我想要更改 LinearLayout 背景,而不是 ImageButton 背景。我怎样才能创建一个像上面的选择器一样的 XML 选择器,但这实际上改变了 LinearLayout 的背景而不是 ImageButton 背景?
先感谢您!! =)
将选择器设置为您的LinearLayout
并添加android:descendantFocusability="blocksDescendants"
to it.
在选择器中,将所有按钮背景替换为布局背景。
<LinearLayout
android:id="@+id/homeButtonLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/layout_bg_selector"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
<ImageButton
android:id="@+id/homeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:background="@drawable/home_icon"
android:onClick="goBackToCameraScreen" />
</LinearLayout>
选择器layout_bg_selector.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#F0F0F0" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="#00F000" /> <!-- focused -->
<item android:drawable="#0000F0" /> <!-- default -->
</selector>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)