在Android中触摸多个图像

时间:2011-07-03 10:24:34

标签: android imageview touch-event

我有这个main.xml文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
>

<ImageView 
    android:id="@+id/img1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/z01"
    />
<ImageView 
    android:id="@+id/img2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/z02"
    />

</LinearLayout>

我想要实现的目标是:

  • 当用户触摸并按住img1时,图片会变为按下的图片(即从z01.png更改为z01_pressed.png)
  • 当(例如)用户在他按住时从img1移动到img2时,img2被按下(将其图片从z02.png更改为z02_pressed.png)并且img1返回其状态(到z01.png)。

要实现这一点,我在onCreate方法中写了这个:

    final ImageView img1 = (ImageView) findViewById(R.id.img1);
    final ImageView img2 = (ImageView) findViewById(R.id.img2);

    img1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            img1.setBackgroundResource(R.drawable.z01_pressed);
            return false;
        }
    });
    img2.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            img2.setBackgroundResource(R.drawable.z01_pressed);
            return false;
        }
    });

然而,这不起作用。我错了吗?

2 个答案:

答案 0 :(得分:0)

您可以使用按钮并将自定义图像设置为该按钮的可绘制对象。这样,您就不必自己管理压缩和未压缩状态。看到这个链接:

http://blog.androgames.net/40/custom-button-style-and-theme/

答案 1 :(得分:0)

对于那些可能感兴趣的人:

这可以使用OnDragListener完成。它需要一些工作才能实现这一目标。我放弃了这一点,让我的生活更轻松。