0

This code is under the on click listener and also under the on create method, and time i click on the textView or loads the page it stops running and write Unfortunately, appName has stopped.

   for (int i = 0 ; i < MAX_BUTTONS; i++){
       Button button = (Button) getLayoutInflater().inflate(R.layout.button_layout,buttonsContainer,false);
       button.setText("Test" + i);
       button.setOnClickListener((View.OnClickListener) this);
       buttonsContainer.addView(button);

       if (i != MAX_BUTTONS - i){
           buttonsContainer.addView(new Space(this),new ViewGroup.MarginLayoutParams(buttonsSpacing,buttonSize));
       }

   }
Akanni
  • 3
  • 2

2 Answers2

0

I think it's because of your cast in setOnClickListener. Just use "this" as a parameter no casting is necessary if your class implements the listener. Also please note that you are creating unecessary object garbage by calling getLayoutInflater in a loop. All you need to do is call it once outside the loop, and use its reference. That way instead of creating n+ objects you only create one. Lastly i see that you're calling

  if(i != MAX_BUTTONS - i) 

didn't you mean

if(i != MAX_BUTTONS - 1)
Bryan Mills
  • 115
  • 9
0

It looks like you may need to create a new Button object each iteration of the loop rather than inflating a layout, for example

   for (int i = 0 ; i < MAX_BUTTONS; i++){
       Button button = new Button(this);
       button.setText("Test" + i);
       button.setOnClickListener((View.OnClickListener) this);
       buttonsContainer.addView(button);

       if (i != MAX_BUTTONS - i){
           buttonsContainer.addView(new Space(this),new ViewGroup.MarginLayoutParams(buttonsSpacing,buttonSize));
       }

   }

Since you are creating the Button programmatically you may want to check this answer for creating LayoutParams.

EDIT: I wanted to mention I agree with Bryan Mill's answer in regard to you if your Activity implements View.OnClickListener you can construct your listener by only passing the context for example, button.setOnClickListener(this), as well as you perhaps meant to write if(i != MAX_BUTTONS - 1) instead of -i.

Community
  • 1
  • 1
Alexi V.
  • 143
  • 1
  • 2
  • 10