android - 在图像中制作多个可点击区域

标签 android android-layout android-activity android-button

我有一张图片,如果用户点击了图片的不同部分,我想执行不同的操作。

我有点像新的爱好者,所以我不理解我在研究中发现的一切。 我找到了几个解决方案,但我不太了解如何实现任何解决方案

  1. Mask the image and get the pixel color of that underneath image to know which area has been clicked

  2. ImageMap

附言:

  • 图像像表格一样在一个网格中(如果有帮助的话)(绘制表格不是一个选项)
  • 我见过其他几个解决方案,但我不理解它们,所以请不要标记为重复。我能理解这些答案背后的想法,但我无法实现它们。我不知道如何处理答案中提供的代码。

我已经成功制作了一些透明按钮并将它们放置在图像上,但是在不同屏幕上进行测试时按钮会从它们的相对位置移动。 我将不胜感激在按钮方面的帮助,或者解释一种不同的方法来做到这一点。

最佳答案

使用 PercentRelativeLayout 在图像上添加按钮层 https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html

首先添加一个库:

dependencies {
    compile 'com.android.support:percent:25.3.1'
}

然后在你的布局文件中:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="200dp"
        android:background="@android:color/black" />

    <android.support.percent.PercentRelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="100dp"
        android:layout_height="200dp">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            app:layout_heightPercent="50%"
            app:layout_marginLeftPercent="25%"
            app:layout_marginTopPercent="25%"
            app:layout_widthPercent="50%" />
    </android.support.percent.PercentRelativeLayout>

</RelativeLayout>

此按钮将位于图像的中心。 如果您想放置在其他地方,您可以使用像素计算您的位置并在预览中看到它。 按钮应该有透明背景。

关于android - 在图像中制作多个可点击区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43699487/

相关文章:

android - setOnItemClickListener 不响应自定义 ListView

android - URLConnection.getContentLength() 返回 -1

Android Activity 工具栏向上按钮不显示

java - 当使用 activity.recreate() 屏幕闪烁黑色 0.5 秒

Android:从堆栈中删除 Activity

java - 如何从 SQLiteOpenHelper 访问 StartActivityForResult()?

android - 使用 retrofit2 和 OkHttp3 时出现此错误。无法解析主机 "<host-name>": No address associated with hostname

java - 如何使用 Intent 将 ArrayList 传递给另一个 Activity?

android - TextView 椭圆大小在 RelativeLayout 中不起作用

android - 复选框按钮设置为空时的波纹效果位置