【问题标题】:ImageView with two images and two onClickListeners?ImageView 有两个图像和两个 onClickListener?
【发布时间】:2016-12-21 00:24:30
【问题描述】:

我有一个imageview,里面有两张图片:

    Resources r = getResources();
    Drawable[] layers = new Drawable[2];
    layers[0] = r.getDrawable(R.drawable.image1);
    layers[1] = r.getDrawable(R.drawable.image2);
    LayerDrawable layerDrawable = new LayerDrawable(layers);
    imageView.setImageDrawable(layerDrawable);

现在,我想在这个imageView 的每张图片上添加一个onClickListener。我该如何解决这个问题?此外,它们不重叠。

谢谢。

--- 编辑 ---

现在,就我而言,我有两个这样的三角形:

我想检测左下角三角形和右上角三角形的点击。

有什么建议吗?

【问题讨论】:

  • 我有 2 个想法来解决它,第一个是有 2 个具有不同可绘制对象的图像视图并为每个图像设置 onclicklistener,另一个想法是使用 setOnTouchListener 进行图像视图并检测用户触摸的坐标。
  • 点击监听器被添加到整个视图,而不是图像。您可以检测到您在视图中点击的位置,但这需要搞乱我猜您不想做的数学运算
  • 你的第一个想法简单易实现
  • 好的,感谢您的快速回复。你能为第一个解决方案举个例子吗?因为我不知道如何将 onclicklistener 添加到 drawable
  • 如果你知道你的视图显示的确切位置,如果你像我一样懒得做数学运算,并且在它们上面有两个透明视图并设置点击,我还有另一个技巧给你。用户不会知道,但它的两个附加视图:P

标签: android imageview onclicklistener


【解决方案1】:

不要使用OnClickListener,使用OnTouchListener。测量位置 touch 事件并使用它来确定点击发生的位置。

imageButton.setOnTouchListener(new OnTouchListener() {
    long lastPress = 0L
    final long CLICK_DURATION = 500L
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            lastPress = System.currrentTimeMillis();
            return true;
        } if(event.getAction() == MotionEvent.ACTION_UP){

            //The time between pressing and releasing has to be below a
            //certain treshold to be a valid click.
            if (System.currentTimeMillis() - lastPress < CLICK_DURATION) {
                int x = (int) event.getX();
                int y = (int) event.getY();

                // Determine which triangle got clicked and then execute
                // the code that would go in an onClickListener.
            }
            return true;
        }
        return false;
    }
}

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多