【问题标题】:Design dynamic hotspot on Image in Android在 Android 中的 Image 上设计动态热点
【发布时间】:2012-10-02 02:17:16
【问题描述】:

我必须开发如下 UI:

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

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

【问题讨论】:

  • 嗨@dev_android 你有运气吗?我在使用多分辨率设备时遇到了同样的问题。
  • 是的,我在人体图像上方添加了一张不可见的多色图像。当用户触摸屏幕时,我计算触摸点的颜色并识别区域。

标签: android imageview onclicklistener


【解决方案1】:

将您的主布局设为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 手机种类繁多。那么如何通过硬编码所有点来处理这个问题。
  • 嗨@DeepikaLalra 你有什么解决方案来处理各种安卓设备吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多