android - 在 Android 的 Image 上设计动态热点

标签 android imageview onclicklistener

我必须开发如下 UI:

enter image description here

我想显示这种类型的图像并在该图像上显示热点。热点的位置将是动态的,根据 x、y 和半径,前提是在原始图片上绘制圆。用户可以点击热点,onclick Action 将定义在用户点击的特定热点上。

开发此类 UI 的最佳流程是什么?

最佳答案

将您的主布局设为 RelativeLayout,然后您可以使用以下代码以编程方式将带有 onClickListenerImageView 添加到您的布局中:

private void addImageView(RelativeLayout mainLayout, int x, int y, int width, int height, OnClickListener onClickListener){
    ImageView imageView = new ImageView(this);
    imageView.setAdjustViewBounds(false);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.height = height;
    params.width = width;
    imageView.setLayoutParams(params);
    imageView.setScaleType(ImageView.ScaleType.FIT_XY);  //remove this if you want to keep aspect ratio
    imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher)); //here goes your drawable
    params.leftMargin = x - width/2;
    params.topMargin = y - height/2;
    imageView.setOnClickListener(onClickListener);
    mainLayout.addView(imageView);
}

调用它来使用它:

    RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout); //this is your main layout
    addImageButton(mainLayout, 200, 300, 200, 200, new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
        }
    });

您也可以使用 ImageButton 来实现相同的目的,尽管图像大小会受到按钮边框的影响:

private void addImageButton(RelativeLayout mainLayout, int x, int y, int width, int height, OnClickListener onClickListener){
    ImageButton imageButton = new ImageButton(this);
    imageButton.setAdjustViewBounds(true);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.height = height;
    params.width = width;
    imageButton.setLayoutParams(params);
    imageButton.setScaleType(ImageView.ScaleType.FIT_XY);
    imageButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
    params.leftMargin = x - width/2;
    params.topMargin = y - height/2;
    imageButton.setOnClickListener(onClickListener);
    mainLayout.addView(imageButton);
}

试一试。

关于android - 在 Android 的 Image 上设计动态热点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12839182/

相关文章:

java - 处理多个按钮的 android onclick(总共 81 个)

android - RecyclerView.OnClickListener 与 View.OnClickListener

java - 如何在自定义android对话框中设置按钮?

android - 在 Android 应用程序中获取 Dropbox URL

ios - imageView 在 xcode9 中不显示图像

android - 试图从屏幕 Android 中删除一个 fragment

android - 为什么 Room 实体不适用于 Android 中的不可变属性

Android - 检查一个 EditText 输入框,每次输入一个字符

android - match_parent 高度内的 ImageView 居中图像

android - 聚焦或单击时如何突出显示 ImageView?