单击视图时,在视图上显示透明颜色突出显示



所以。您知道,当您点击Google+应用中的帖子时,整个视图会变成蓝色。我也想这样做,但使用ImageView。

我有以下代码片段,将实际图像设置为背景,将选择器设置为主要资源。这看起来不错,但不考虑背景图像的 scaleType:

      <ImageView
            android:id="@+id/painting_image"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@drawable/img"
            android:src="@drawable/selector"
            android:scaleType="centerCrop" />

顺便说一下,@drawable/selector只是一个选择器,显示state_pressed的父色:

<item android:state_pressed="true">
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid android:color="#44521400" />
    </shape></item>

如何在尊重 scaleType 的同时完成这项工作?

ImageView包装在FrameLayout中,并定义可单击的FrameLayout。小心将onClick事件分配给FrameLayout,而不是ImageView,否则效果会破坏!另请注意,foreground已设置为选择器,而不是background

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:clickable="true"
        android:foreground="@drawable/imagebutton_selector" >
        <ImageView
            android:id="@+id/painting_image"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:scaleType="centerCrop" />
    </FrameLayout>

ScaleType 仅适用于 src 可绘制对象,而不应用于背景。考虑将第二个选项与叠加视图一起使用,您将在其中实现点击操作,如下所示:

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <ImageView
            android:id="@+id/painting_image"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:scaleType="centerCrop" />
        <View
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:background="@drawable/imagebutton_selector"
            android:onClick="onImageClick" />
     </FrameLayout>

最新更新