-4

Currently im making a soundboard like app. Becouse i have around 60 sounds it would take ages to create function for every single one. So I ran into idea, is it possible to detect press of any of these buttons and then get its id? It will be very helpful, becouse the buttons ids are also corresponding music file names. Thanks for any help.

Ege Kuzubasioglu
  • 5,991
  • 12
  • 49
  • 85
MSSC
  • 38
  • 2
  • 9
  • 1
    Simple google search led me here, probably might answer your question, look [here](http://stackoverflow.com/questions/13032333/droid-how-to-get-button-id-from-onclick-method-described-in-xml) And if that is not enough look [here](http://stackoverflow.com/questions/3320115/android-onclicklistener-identify-a-button) This question has been answer lioke a dozen times. next time look the net! – Mercury Mar 26 '17 at 07:21
  • 3
    Possible duplicate of [Droid: How to get button id from onClick method described in XML?](http://stackoverflow.com/questions/13032333/droid-how-to-get-button-id-from-onclick-method-described-in-xml) – Lennart Mar 26 '17 at 17:00

1 Answers1

1

From the question, it was not immediately clear that you are seeking a way to retrieve information encoded in your choice of ID string names rather than to simply use a single handler for all of your buttons, for which getId alone is typically sufficient.

The resource name for a View ID can be extracted from an ID using View.getResources().getResourceName(id). (1)

The result is a reusable listener that obtains the file names by extracting the view ID and looking up the resource name:

View.OnClickListener mSoundClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String resourceName = view.getResources().getResourceName(view.getId());
        mySoundHandler(resourceName);
    }
};    

You can then attach the handler to each button.

button1.setOnClickListener(mSoundClickListener);
button2.setOnClickListener(mSoundClickListener);
//....
user650881
  • 2,214
  • 19
  • 31