glassraven glassraven - 24 days ago 6
Android Question

How to set onclick views dinamically in Android?

this a program for a musical instrument. I have 10 keys(buttons) for each sound, and a different media player associated to it. I've created a method for each key, but as you can see, the code is always the same; the only thing that changes is the media player...This works fine, but i'm asking if there is a better way to do this, something more dynamic?

public void one() {
first = MediaPlayer.create(this, R.raw.dokey);
first.start();
first.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}



@Override
public void onClick(View v) {
if(v==key1){ //key1 is the button
one();
}
//and so on...
}
}

Answer

Without knowing too much of your code, I think you could extract the clicklistener and do something like this:

private class OnKeyClickListener implements View.OnClickListener {

    private MediaPlayer mMediaPlayer;

    public OnKeyClickListener(MediaPlayer mediaPlayer) {
        mMediaPlayer = mediaPlayer;
    }

    @Override public void onClick(View view) {
        /// do the thing
    }
}

And than add that to the keys:

MediaPlayer mediaPlayer1 = new MediaPlayer(); // mediaplayer for key 1
key1.setOnClickListener(new OnKeyClickListener(mediaPlayer1));

MediaPlayer mediaPlayer2 = new MediaPlayer(); // mediaplayer for key 2
key2.setOnClickListener(new OnKeyClickListener(mediaPlayer2));

EDIT 1: Alternatively, you could add the mediaplayer as the tag for the View.

key1.setTag(mediaplayer1);

And then in onClick get the clicked views tag and cast that to a mediaplayer.

onClick(View v) {
    Mediaplayer mediaplayer = (MediaPlayer) v.getTag();
}