0

我有这个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;
        }
    });

但是,这不起作用。我有什么问题吗?

4

2 回答 2

0

您可以使用按钮并将自定义图像设置为该按钮的可绘制对象。这样,您就不必自己管理已按下和未按下的状态。请参阅此链接:

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

于 2011-07-03T10:28:26.183 回答
0

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

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

于 2012-01-12T00:53:09.233 回答