2013-11-01 75 views
5

我有一个带有ImageView和TextView的LinearLayout“卡片”。我希望卡片在用户点击时突出显示。示例请参见http://www.youtube.com/watch?v=Yx1l9Y7GIk8&feature=share&t=15m17s当用户点击它时,ImageView上的蓝色突出显示

通过设置android:background="@drawable/blue_highlight"可以轻松完成TextView的工作。下面是RES /绘制/ blue_highlight.xml:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_selected="true" android:drawable="@color/selected"/> 
    <item android:state_pressed="true" android:drawable="@color/pressed"/> 
    <item android:drawable="@color/bg_window"/> 
</selector> 

但因为图像是在前面,背景是不可见的,这并不为ImageView的工作。如何使用半透明颜色为ImageView创建触摸突出显示效果?

+2

我相信你可以把你的LinearLayout放到FrameLayout中并为它设置前景属性。 – Bracadabra

回答

12

令人惊讶的是,FrameLayout有foreground属性可用于此。缺点是你必须添加一个额外的FrameLayout元素。这个实现很简单,所以直到你有时间去实现花哨的图像处理(使图像变色一点,然后应用突出显示)以及动态构建状态drawable时,这似乎就足够了。

所以在我的情况下,这将是:

<FrameLayout 
    android:foreground="@drawable/blue_highlight_image" 
    > 
    <ImageView ...> 
</FrameLayout> 

@绘制/ blue_highlight_image采用按压的新@颜色/ pressed_image值,它是与@颜色相似/但是具有alpha通道,例如:#81CFEB - >#AA81CFEB。

感谢@Vang的建议。

+1

对于默认的蓝色,您可以使用:'?android:attr/selectableItemBackground'。 –

+0

这很好,和@aleb提到它一样,我用alpha 30%使它看起来像高亮(十六进制中的30%alpha = 4D)。 – green0range

1

你是对的。尝试使用blue_highlight.xml作为您的drawable,但是使用那里的颜色使用您想要显示的图像,并定义第二个drawable,当突出显示时向图像添加颜色过滤器。

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_selected="true" android:drawable="@drawable/yourdrawable_with_colorfilter"/> 
    <item android:state_pressed="true" android:drawable="@drawable/yourdrawable_with_colorfilter"/> 
    <item android:drawable="@drawable/your_drawable"/> 
</selector> 
+0

谢谢。可能对静态图像很有效。如果图像来自数据库或下载,则更难实现。 – aleb

+0

你说得对。但是你没有提到这一点。为了更具动态性,您可以编程选择器。 [这里](http://stackoverflow.com/questions/4697528/replace-selector-images-programmatically)你可以找到一个很好的例子(接受的答案)。 – Baschi

相关问题