开发者

Touching Multiple Images With Hold In Android

I have this main.xml file:

<?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="f开发者_开发问答ill_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>

What I am trying to achieve is:

  • when the user touch and hold img1, the picture changs to the pressed pic (i.e. changed from z01.png to z01_pressed.png)
  • when (for example) the user moves from img1 to img2 while he holding, img2 get pressed (changed its picture from z02.png to z02_pressed.png) and img1 returns to its state (to z01.png).

to achieve this, I wrote this in onCreate method:

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

However, this does not work. Am I getting something wrong?


You can use a button and set a custom image as the drawable of that button. That way, you won't have to manage the pressed and unpressed states yourself. See this link:

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


To those who might be interested:

This can be done using OnDragListener. It needs some work to accomplish this. I gave up on that to make my life easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜