在Android中设计Image上的动态热点

时间:2012-10-11 12:08:17

标签: android imageview onclicklistener

我必须开发如下的用户界面:

enter image description here

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

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

1 个答案:

答案 0 :(得分:0)

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

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);
}

试试吧。