2014-02-17 2 views
1

Я разрабатываю приложение для фортепиано для Android. Я пытаюсь реализовать OnTouchListener для всех 8 кнопок, которые у меня есть в моей деятельности. Поэтому, когда пользователь тащит или проводит пальцем, я хочу, чтобы все кнопки воспроизводили звук. Я думаю, что приведенная ниже картина объясняет это лучше.OntouchListener перетащить через кнопки

См? Когда пользователь поместит руку на первую кнопку, а затем перетащит до последней кнопки, я хочу, чтобы все 8 кнопок воспроизводили песню. Но я не могу этого добиться. Ниже java-код работает только для первой кнопки, но остальные 7 кнопок не нажимаются.

Здесь:

@Override 
public boolean onTouch(View v, MotionEvent event) { 
    switch(v.getID()) 
    { 
     case(R.id.btn1): 
     //play button 1 sound 
     break; 

     case(R.id.btn2): 
     //play button 2 sound 
     break; 

     case(R.id.btn3): 
     //play button 3 sound 
     break; 

     case(R.id.btn4): 
     //play button 4 sound 
     break; 

     case(R.id.btn5): 
     //play button 1 sound 
     break; 

     case(R.id.btn6): 
     //play button 6 sound 
     break; 

     case(R.id.btn7): 
     //play button 7 sound 
     break; 

     case(R.id.btn8): 
     //play button 8 sound 
     break; 
     }   
    return true; 
    } 

Я уже видел this вопрос и this как хорошо, но не смогли найти ответ там.

Пожалуйста, помогите мне. Благодарю вас за время!

+0

Кто-то ????? Пожалуйста, помогите мне! –

ответ

0

Вы должны реализовать onTouchListner на макете, который содержит кнопки пианино

Идея заключается в том, чтобы получить все позиции кнопок пианино на экране (х, у) после того, как сделать их.

затем получите контактную позицию с помощью методов getX() и getY().

На этом этапе вы можете справиться с этим, проверяя, если сенсорный х и у находится между началом просмотра и

конца х и у, а затем воспроизводить звук зрения.

В этом примере я использую soundpool и pitch для воспроизведения разных звуков (я знаю, что это не идеальный способ), и я также работаю с коэффициентом x только потому, что я использую только клавиши фортепиано.

import android.app.Activity; 
import android.media.*; 
import android.os.Bundle; 
import android.view.*; 
import android.widget.*; 

import java.util.ArrayList; 
import java.util.List; 


public class MainActivity extends Activity 
{ 

    //The layout that holds the piano keys. 
    LinearLayout pianoKeysContainer; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     pianoKeysContainer = (LinearLayout) findViewById(R.id.key_container); 
     pianoKeysContainer.setOnTouchListener(onYourViewTouchListener); 
    } 


    //Here we load the view positions after render it and fill the array with the positions 
    private List<Integer> positionsLeft_whiteKeys = new ArrayList<Integer>(); 
    private List<Integer> positionsRight_whiteKeys = new ArrayList<Integer>(); 

    public void onWindowFocusChanged(boolean hasFocus) 
    { 
     super.onWindowFocusChanged(hasFocus); 

     for (int i = 0; i < pianoKeysContainer.getChildCount(); i++) 
     { 
      //positionsLeft_whiteKeys holds the start x of each view. 
      positionsLeft_whiteKeys.add(pianoKeysContainer.getChildAt(i).getLeft()); 
      //positionsRight_whiteKeys holds the end x of each view. 
      positionsRight_whiteKeys.add(pianoKeysContainer.getChildAt(i).getRight()); 
     } 
    } 

    public View.OnTouchListener onYourViewTouchListener = new View.OnTouchListener() 
    { 
     float positionX; 
     FrameLayout pianoKey; 
     FrameLayout lastPlayedKey; 
     ArrayList<FrameLayout> pressedKeys = new ArrayList<FrameLayout>(); 

     @Override 
     public boolean onTouch(View view, MotionEvent motionEvent) 
     { 

      positionX = motionEvent.getX(); 

      float pitch; 

      //Looping on the child of the layout which contains the piano keys 
      for (int x = 0; x < ((LinearLayout) view).getChildCount(); x++) 
      { 
       // Calculating the pitch to get good chords 
       pitch = (float) Math.pow(Math.pow(2.0, 1/12.0), (float) x); 

       pianoKey = (FrameLayout) ((LinearLayout) view).getChildAt(x); 

       if (positionsLeft_whiteKeys.size() >= 0 && positionsRight_whiteKeys.size() >= 0) 
       { 
        if (positionX > positionsLeft_whiteKeys.get(x) && positionX < positionsRight_whiteKeys.get(x)) 
        { 
         pianoKey = (FrameLayout) ((LinearLayout) view).getChildAt(x); 

         if (pianoKey != null) 
         { 
          pianoKey.setBackgroundResource(R.drawable.piano_key_pressed); 
          pressedKeys.add(pianoKey); 
         } 
         if (lastPlayedKey != pianoKey) 
          playKey(pitch); 

         lastPlayedKey = pianoKey; 
         break; 
        } 

        if (lastPlayedKey != null) 
        { 
         pianoKey.setBackgroundResource(R.drawable.piano_key); 
         lastPlayedKey.setBackgroundResource(R.drawable.piano_key); 

        } 
       } 
      } 

      if (motionEvent.getAction() == MotionEvent.ACTION_UP) 
      { 
       lastPlayedKey = null; 

       for (FrameLayout pressedKey : pressedKeys) 
       { 
        pressedKey.setBackgroundResource(R.drawable.piano_key); 
       } 


      } 

      return false; 
     } 
    }; 


    //This is sound play method 
    SoundPool sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 1); 
    public void playKey(final float pitch) 
    { 

     //here you should store your piano sound at res/raw then load it 
     sp.load(this, R.raw.piano, 1); 

     sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() 
     { 
      @Override 
      public void onLoadComplete(SoundPool soundPool, int i, int i2) 
      { 
       soundPool.play(i, 0.99f, 0.99f, 1, 0, pitch); 
      } 
     }); 
    } 

} 

И это файл XML (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="match_parent" 
       android:layout_height="match_parent"> 

    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:clickable="true" 
     android:id="@+id/key_container"> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key" 
      /> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

     <FrameLayout 
      android:layout_height="match_parent" 
      android:layout_marginRight="2dp" 
      android:layout_width="48dp" 
      android:background="@drawable/piano_key"/> 

    </LinearLayout> 


</LinearLayout> 

Примечание: единственное, что вы должны сделать, чтобы закончить пример, чтобы положить вам клавишная изображение (нажатие и не нажата) и поставить звук фортепьяно при res/raw

Смежные вопросы