José Leal
José Leal

Reputation: 8109

Android touch screen listener problem

i've created this little program to show the user the fingers on the screen, but the problem is that the X,Y values from the other fingers are not being modified. What am I doing wrong?

Thank you!

public class TestandoActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
private TextView txtV;
private TextView txtV2;
private int nf = 0;
private Map<Integer, String> info;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    info = new HashMap<Integer, String>();

    setContentView(R.layout.main);
    this.txtV = (TextView)this.findViewById(R.id.textview);
    this.txtV2 = (TextView)this.findViewById(R.id.textview2);
    this.txtV.setOnTouchListener(this);
}

public boolean onTouch(View v, MotionEvent event) {     
    int actionCode = event.getAction() & MotionEvent.ACTION_MASK;
    int pid = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;

    info.put(pid, pid + ": X=" + event.getX() + " Y=" + event.getY() + " pressure=" + event.getPressure() + " size=" + event.getSize());

    if (actionCode == MotionEvent.ACTION_POINTER_UP || actionCode == MotionEvent.ACTION_UP)
        info.remove(pid);

    String total = "";
    for (Map.Entry<Integer, String> e : this.info.entrySet()) {
        total += e.getValue() + "\n";
    }

    this.txtV2.setText(total);


    return true;
}
}

Upvotes: 0

Views: 2167

Answers (1)

Chickenrice
Chickenrice

Reputation: 5727

The main cause of this problem is that you used getX() and getY() method.

getX() method always returns the first pointer's x position and getY() returns its y position.

If you want to get other fingers' X, Y value on the screen, you have to use these methods:

getX(int pointerId)  //get #pointerId pointer's x value
getY(int pointerId)  //get #pointerId pointer's y value

Other fingers' pointerId can be found by the way you're using:

int pid = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;

Or use pointer index to get ID:

getPointerId (int pointerIndex)   //pointerIndex is from 0 to getPointerCount()-1

I hope it will be helpful to you. :)

Upvotes: 1

Related Questions