android - 如何让 ImageButton 表现得像 ViewGroup?

标签 android button textview imageview

我想要一个图像,在图像上我想放置一个较短的半透明 View 并在该 View 内放置一个 TextView ,最后我想要所有这些可点击的显示基本点击效果的按钮。

我不会用

<Button>
   <ImageView>
      <TextView/>
   </ImageView>
</Button>

我可以创建一个带有 Clickable=true 的 LinearLayout。但是如何模仿按钮上存在的视觉按压效果呢?

更新:我添加了一张图片,展示了我希望它如何显示。把它想象成一个 ImageButton(它应该有打印效果)

enter image description here

UPDATE-2:我添加了另一张显示按下效果的图片。 (类似于 Play 商店应用)。 enter image description here

最佳答案

创建包含图像和文本等的 ViewGroup(例如 LinearLayout/RelativeLayout 等)

使此 ViewGroup 可点击(例如,通过为其分配一个 OnClicListener)。

为这个 ViewGroup 分配一个background drawable。

确保此背景可绘制对象是状态列表可绘制对象: https://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

将适当的可绘制对象分配给各种状态(最重要的是 state_pressed,但您可能还想处理其他状态)。

当用户按下按钮时,将显示相应的可绘制对象,并且看起来就像 ViewGroup 是一个按钮(可以按下的东西)。

在 OP 显示按下状态的新图像后更新:

添加一个位于图像/文本/等之上的 View ,其背景具有 StateListDrawable:

<RelativeLayout >
    <ImageView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/somerealpngfile"
        ... 
    />
    <TextView  
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        ... 
    />
    <View 
        android:id+"@+id/clickable_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/selectable_background"
        android:clickable="true"

        ... 
    />
</RelativeLayout>

res/drawable/selectable_background.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/grid_state_pressed"/>
    <item android:state_focused="true" android:drawable="@color/grid_state_focused"/>
    <item android:drawable="@android:color/transparent"/>
</selector>

res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  ...
  <color name="grid_state_pressed">#BB7dbcd3</color>
  <color name="grid_state_focused">#777dbcd3</color>
  ...
</resources>

其中颜色 grid_state_pressedgrid_state_focused 是半透明的(即它们的 alpha 小于 255)。

当用户单击您的“按钮”时,带有 R.id.clickable_view 的 View 将处理 onClick 并将更改其背景颜色,从而使图像和文本以半透明的方式闪耀。

关于android - 如何让 ImageButton 表现得像 ViewGroup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092436/

相关文章:

android - 如何在适配器 ListView 中添加 onclick 按钮

java - 在 View 类中保存 sharedPreferences

android - 在 RelativeLayout 中替代 weightSum?

c# - 为什么这个按钮的 OnClick 事件只工作一次?

android - 如何创建FloatingActionButton菜单

android - 在运行 Flask 服务的 GCP App Engine 服务上接收图像时出现问题

Android Marquee TextView 可点击链接

java - Android Studio 看不到 TextView ID

android - 如何使用支持库字体功能作为 TextView 内容的一部分(使用 spannable)?

JavaScript 按钮