12

I dynamically created buttons through code rather than from XML.
The code is as below :

    dynamicview = (LinearLayout)findViewById(R.id.llayout);
     LinearLayout.LayoutParams lprams = new LinearLayout.LayoutParams(
             LinearLayout.LayoutParams.WRAP_CONTENT,
             LinearLayout.LayoutParams.WRAP_CONTENT);

     for(int i=0;i<nob;i++){
         Button btn = new Button(this);
         btn.setId(i+1);
         btn.setText("Button"+(i+1));
         btn.setLayoutParams(lprams);
         dynamicview.addView(btn);
     }


I am not finding a way in which I can implement OnClickListener to each of these buttons so that I can perform action based on the reference I get.
Can anyone help me in sorting out this issue. ?
Thanks in Advance,

user1276092
  • 523
  • 3
  • 8
  • 30
  • The provided answers are correct. The view passed into the onClickListender is the Button and can be cast. Button btn = (Button)v; Then used to access the id that you set. – madmik3 May 20 '12 at 13:07

6 Answers6

30

See the code below:

for(int i=0;i<nob;i++) {
    Button btn = new Button(this);
    btn.setId(i+1);
    btn.setText("Button"+(i+1));
    btn.setLayoutParams(lprams);
    final int index = i;
    btn.setOnClickListener(new OnClickListener() {
        void onClick(View v) {
            Log.i("TAG", "The index is" + index);
        }
    });
    dynamicview.addView(btn);
}

My example is pretty simple, but demonstrates how you can get the button index into the OnClickListeber. You can access any final field in the declared anonymous classes (e..g the OnClickListener).

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • what if I want to perform some other action on different button ? I think If I write some code in your click listener It will be same FOR ALL OF THE BUTTONS, how can I achieve different functionality on each button? – Cyph3rCod3r Feb 05 '14 at 03:46
  • 2
    @Dr.aNdRO Logical question with simple answer. In order to have different functionality you need to define different `OnClickListener`s. Do it in whatever manner you like and just fill them in an array `OnClickListener [] listeners`. Then in the for do `btn.setOnClickListener(listeners[i]);` – Boris Strandjev Feb 05 '14 at 07:16
8
   for(int i=0;i<nob;i++){
         Button btn = new Button(this);
         btn.setId(i+1);
         btn.setText("Button"+(i+1));
         btn.setOnClickListener(btnclick); <<<<<<<set click
         btn.setLayoutParams(lprams);
         dynamicview.addView(btn);
     }

And add this listner outside the any method and inside class

 OnClickListener btnclick = new OnClickListener() {

        @Override
        public void onClick(View view) {

            switch(view.getId()){
              case 1:
               //first button click
              break;
               //Second button click
              case 2:
              break;
              case 3:
               //third button click
              break;
              case 4:
               //fourth button click
              break;
            .
            .
            .
             default:
              break;
              }

        }
    };
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • the order in this corde is incorrect. you want to make the listener prior to the loop. – madmik3 May 20 '12 at 13:10
  • 1
    not a proper solution as I would not know the number of buttons before hand and moreover I would not want to add a case for each button. – Arif Nadeem May 20 '12 at 13:13
  • @mirroredAbstraction this is most proper soluton for each button click...and if you dont for all then need only onclick method – Samir Mangroliya May 20 '12 at 13:17
2

Use a List and add Buttons you create to that List

List<Button> list = new ArrayList<Button>();

Now add your button to that List

for(int i=0;i<nob;i++){
         Button btn = new Button(this);
         btn.setId(i+1);
         btn.setText("Button"+(i+1));
         btn.setLayoutParams(lprams);
         dynamicview.addView(btn);
         list.add(btn);
     }

Then use advanced for loop to iterate through the list and add click listener for each Button..

for(Button btn : list){
btn.setOnClickListener(this);
}
Arif Nadeem
  • 8,524
  • 7
  • 47
  • 78
2

Maybe this will be helpful for somebody I wanted to use the one counter variable for group of dynamically created buttons:

I've created the array for counters:

int[] squatReps;

From preferences I've taken the quantity of elements:

squatReps = new int[squatSets];  // where squatSets is taken from preferences

And finally we create the buttons

for (int i = 0; i < squatSets; i++){
                squatReps[i] = Integer.parseInt(sharedPreferences.getString("squats_reps", "0"));
                final Button squat_b = new Button(this.getActivity());
                squat_b.setId(i);
                squat_b.setText("");
                squat_b.setLayoutParams(layoutParams);
                final int index = i;
                squat_b.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        squat_b.setText(Integer.toString(squatReps[index]--));    
                        startTimer();                                
                    }
                });
                panel_1.addView(squat_b);
Leo240
  • 766
  • 7
  • 16
1

its the same thing...

for(int i=0;i<nob;i++){
         Button btn = new Button(this);
         btn.setId(i+1);
         btn.setText("Button"+(i+1));
         btn.setLayoutParams(lprams);
         btn.setOnCLickListsener(new listener());
         dynamicview.addView(btn);
     }

listener implemnets OnClickListenere{

public void onClick(View v){

}

}

ngesh
  • 13,398
  • 4
  • 44
  • 60
1
for(int i=0;i<nob;i++){
         Button btn = new Button(this);
         btn.setId(i+1);
         btn.setText("Button"+(i+1));
         btn.setLayoutParams(lprams);
         btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               /////Do some job on button click
            }
        }); 
         dynamicview.addView(btn);
     }
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213