Java – Android getting touched button’s text with onTouch()

androidjavaview

I'm trying to make something like a drum machine that plays sounds when you press the buttons. However, I'm having trouble making it change sounds for each button, since one onTouch method handles all the events. Here's the code so far:

package com.henzl0l.drummaschine;

import java.io.IOException;

import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.view.MotionEvent;

public class DrumMaschine extends Activity { /** Called when the activity is first created. */ final String[] sList = new String[] {"/sdcard/Music/kick.wav","/sdcard/Music/hat.wav" }; final MediaPlayer mPlayer1 = new MediaPlayer(); final MediaPlayer mPlayer2 = new MediaPlayer(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Button btn_main1 = (Button) findViewById(R.id.cmd_main1); Button btn_main2 = (Button) findViewById(R.id.cmd_main2); btn_main1.setOnTouchListener(tListener1); btn_main2.setOnTouchListener(tListener1); } private OnTouchListener tListener1 = new OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { switch ( event.getAction() ) { case MotionEvent.ACTION_DOWN: sPlay(0,true); } return false; } }; private void sPlay(Integer num, Boolean loop){ try { mPlayer1.reset(); mPlayer1.setDataSource(sList[num]); mPlayer1.prepare(); mPlayer1.start(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } };

}

I can't seem to get the button's text (Which is right now, '1', '2', etc.) using v, so I'm pretty much stumped. I've only been playing with android for two days now. Sorry if nothing makes sense hehe.

Best Answer

The onTouch method has a View parameter which is a reference to the touched view. Cast this to Button to get its caption:

String caption=((Button)v).getText();

By the way, why are you using onTouchListener? If you only want to detect clicks, use onClickListener, it's simpler (and has the same argument).

Using tags instead of the caption could be another enhancement: you can add tags to views with setTag (it accepts an optional key too) and retrieve them by getTag. You could tag your buttons with your sound sample numbers for example.

Related Topic