伙计们,如果我有这样的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/deals_list_item_bckg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="15dp"
android:background="@drawable/deals_list_item_background"
android:clickable="true"
android:orientation="horizontal" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="85dp"
android:layout_height="50dp"
android:scaleType="fitXY"
android:src="@drawable/btn_unpressed" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="My Account"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
结果是
有什么方法可以编写在按下状态时仅更改 imageView 的 img 的选择器
像这样
或者告诉我我该怎么做这样的按钮,因为问题是按钮的右边部分也需要背景图片,左边部分是 ImageView ,当按下右边部分(布局)时必须改变它的图像
最佳答案
除非您计划在运行时向该按钮布局添加大量 View ……对于您需要它执行的操作而言它过于复杂。这是一个更简单的版本,应该适合您:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="15dp"
android:clickable="true"
android:orientation="horizontal">
<ImageView
android:layout_width="85dp"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:duplicateParentState="true"
android:src="@drawable/btn_background" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:background="@drawable/your_grey_bar"
android:paddingRight="10dp"
android:text="My Account"
android:textSize="16sp" />
</LinearLayout>
然后在 res/drawable 中你需要定义 btn_background.xml 如下:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_default_disabled_focused" android:state_focused="true" android:state_enabled="false"/>
<item android:drawable="@drawable/btn_default_focused" android:state_focused="true" android:state_enabled="true"/>
<item android:drawable="@drawable/btn_default_disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/btn_default_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_default_normal" />
</selector>
这里的技巧是 LinearLayout 是可点击的。这样用户就可以点击“按钮”上的任意位置。然后让 ImageView
复制它的父状态。这意味着只要 LinearLayout 改变它的状态(例如,启用、聚焦、按下等),ImageView 也会接收到它。因此,选择器可绘制对象将执行它的操作并为您更新。
关于带有imageview的可点击布局的android选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319561/