Help Creating Buttons with an Array

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Help Creating Buttons with an Array

Postby larkham » Wed Mar 02, 2011 1:36 am

Hey all, I am (very) new to Java and Android but am looking for a bit of guidance and support. I am working on a soundboard app where I have about 30 different buttons that I've currently hand-coded in. I know that you can use an array to "automate" the creation of these buttons instead of coding them one by one..

Anyway I have two sections that the array should take care of (unless there is a better way?), the first of which is for the sounds. It goes from sound1 to sound33:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. mSoundManager = new SoundManager();
  2. mSoundManager.initSounds(getBaseContext());
  3. mSoundManager.addSound(1, R.raw.sound1);
  4. mSoundManager.addSound(2, R.raw.sound2);
  5. mSoundManager.addSound(3, R.raw.sound3);
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


The second part is the buttons themselves (1 through 33):

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. Button SoundButton1 = (Button)findViewById(R.id.sound1);
  2. registerForContextMenu(SoundButton1);
  3. SoundButton1.setOnClickListener(new OnClickListener() {
  4.         public void onClick(View v) {
  5.                         mSoundManager.playSound(1);
  6.         }
  7. });
  8.  
Parsed in 0.031 seconds, using GeSHi 1.0.8.4



For the Array I think I have the basic concept down, but obviously I am doing something wrong.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. int[] btnList = new int[33];
  2.  
  3. for (int i = 0; i < btnList.length; i++){
  4. mSoundManager.addSound(btnList[i], R.raw.sound[i]);
  5.                        
  6. Button SoundButton[i] = (Button)findViewById(R.id.sound[i]);
  7. registerForContextMenu(SoundButton[i]);
  8. SoundButton[i].setOnClickListener(new OnClickListener() {
  9.         public void onClick(View v) {
  10.                 mSoundManager.playSound([i]);
  11.         }
  12. });
  13. }
  14.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4


I am not sure what I need to do to fix this though. It doesn't like me only using [i], so I see that I should instead be using btnList[i], but in the case of "SoundBoard1" or "sound1", how would I get it to return the number 1? Any help is greatly appreciated!
larkham
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Feb 25, 2011 1:25 am

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests