2011-09-14 37 views
0

我終於想出瞭如何啓用多點觸摸,經過大約一週的試驗和錯誤。但是,我遇到了另一個問題。首先,讓我解釋一下我的應用程序。不同的響應每個不同的觸摸事件

這是一個非常基本的應用程序。當您觸摸屏幕上的AREA_A時,它將播放SOUND_A。當您觸摸屏幕上的AREA_B時,它將播放SOUND_B。很簡單。我希望這可以使用多點觸控,所以我使用了一個OnTouch事件。我現在可以同時觸摸屏幕上的AREA_A和AREA_B,並從兩個區域獲得聲音(證明多點觸控正在工作),但問題來了。如果我開始觸摸AREA_A,並將手指按住,然後觸摸AREA_B(我的第一根手指仍然觸摸AREA_A),而不是聽到SOUND_B,我聽到SOUND_A正在播放。我很困惑,爲什麼會發生這種情況。我認爲如果我粘貼代碼,情況會更加清晰,所以就是這樣。 (我繼續前進,添加了我的整個班級,只是讓你可以從頭到尾查看)。

package com.tst.tanner; 

import android.app.Activity; 
import android.graphics.Color; 
import android.media.AudioManager; 
import android.media.SoundPool; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 


public class sp extends Activity implements OnTouchListener { 
private SoundPool soundPool; 
private int bdsound, sdsound; 
float x, y; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    // Set the hardware buttons to control the music 
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC); 
    // Load the sound 
    View v = (View) findViewById(R.id.view1); 

    v.setOnTouchListener(this); 

    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); 
    bdsound = soundPool.load(this, R.raw.kickdrum1, 1); 
    sdsound = soundPool.load(this, R.raw.sd, 1); 

} 

@Override 
public boolean onTouch(View v, MotionEvent e) { 
    // TODO Auto-generated method stub 
    x = e.getX(); 
    y = e.getY(); 


    v.setBackgroundColor(Color.rgb(236,234,135)); 
    switch (e.getActionMasked()) { 
    case MotionEvent.ACTION_DOWN: 

     if (x > 1 & x < 200 & y > 1 & y < 200) { 
      soundPool.play(bdsound, 10, 10, 1, 0, 1); 
     } 
     if (x > 1 & x < 200 & y > 200 & y < 400) { 
      soundPool.play(sdsound, 10, 10, 1, 0, 1); 
     } 

     break; 

    case MotionEvent.ACTION_POINTER_1_DOWN: 

     if 
     (x > 1 & x < 200 & y > 1 & y < 200) { 
      soundPool.play(bdsound, 10, 10, 1, 0, 1); 
     } 
     if (x > 1 & x < 200 & y > 200 & y < 400) { 
      soundPool.play(sdsound, 10, 10, 1, 0, 1); 
     } 

     break; 


    case MotionEvent.ACTION_UP: 


     v.setBackgroundColor(Color.BLACK); 

    } 

    return true; 
} 

@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 
    soundPool.release(); 
    finish(); 
} 
} 

有誰知道我在做什麼錯?提前致謝!

回答

2

getX()getY()函數總是返回第一個指針的位置。我懷疑這是造成你的問題。

當您將第二根手指觸摸到區域B的屏幕時,MotionEvent的類型爲ACTION_DOWN,因此會播放聲音(就像您所期望的那樣)。但是,由於您首先觸摸了區域A並且仍然觸摸它,該位置是由getX()getY()返回的位置。

要獲取特定指針的位置,請嘗試使用getX(int)getY(int)函數。例如,如果您觸摸屏幕用兩個手指,並希望第二個手指的位置,你會使用

x2 = getX(1); 
y2 = getY(1); 

getX()相同getX(0)getY()相同getY(0)

你可以請查看documentation瞭解更多信息。

+0

非常感謝,這工作! – Tanner