简体   繁体   中英

displaying numbers in BINGO game on button click in Android

I am making a BINGO game in android, where there are 25 buttons as shown in pic. here is the layout Now whenever i will click a button, a number from 1 to 25 to should appear on the clicked button. The problem arises when i want to write a single function, what should i pass as object so that 'the button I clicked -> its object should be invoked -> and only that buttons text should be set as a number.' This is the MainActivity.java file.

public class MainActivity extends AppCompatActivity {

    //made 25 objects for 25 buttons
    public static int cnt=0;

    //button array
    Button butt[]={b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25};

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }

        public void show(View view)
                {
                    cnt++;
                    if(cnt<26)
                    {
                     b1.setText(cnt); //what should i write here for different 
                                      //button objects, so that text for each button 
                                      //is set on clicking, without defining 25 
                                      //different functions
                        }
                    }
        }

On every button click, control comes at show().

The output after clicking all buttons, should have 1 number, from 1 to 25 in each box. Please help!

You can set an OnClickListener foreach button in array:

 public void show(View view)
                    {
                        cnt++;
                        if(cnt<26)
                        {

                             for(int i = 0; i<butt.length; i++){

                                 final Button b = butt[i];

                                 b.setOnClickListener(new View.OnClickListener() {

                                     @Override
                                     public void onClick(View v) {

                                         b.setText("Some number");
                                     }
                                 });
                            }
                        }
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM