Question

Does anybody know how to create buttons for the alphabet (for a hangman-application) in a for loop?
I'm not sure what needs to be done in the java class and what needs to be done in the xml file.

Was it helpful?

Solution

You do not need to do anything in the XML file. This can all be done in a class.

for(int i=0; i < x; i++) // where x is the size of the list containing your alphabet.
{
   Button button = new Button(this);
   button.setId(i);
   yourView.add(button);
}

OTHER TIPS

here you go. but you must also note that your layout must be linear and the orientation must be set depending on how you want your button arranged.

If you use relative view the buttons will stack over each other and it is your last looped button that will be shown.

LinearLayout layout = (LinearLayout) findViewById(R.id.rl_table_of_contents);

        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

        Button[] btn = new Button[your_array];
        for (int i = 0; i < your_array.length(); i++) {
            btn[i] = new Button(getApplicationContext());
            btn[i].setText("Button "+ i);
            //btn[i].setBackground();
            btn[i].setTextSize(20);
            //btn[i].setHeight(100);
            btn[i].setLayoutParams(param);
            btn[i].setPadding(15, 20, 15, 20);
            layout.addView(btn[i]);

            //btn[i].setOnClickListener(handleOnClick(btn[i]));

        }

View.OnClickListener handleOnClick(final Button button) {
    return new View.OnClickListener() {
        public void onClick(View v) {
        }
    };
}
int count=26;
    Button[] btnArray = new Button[26];

    LinearLayout layout=new LinearLayout(this);
    LinearLayout.LayoutParams params=new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

    for(int i=0;i<count;i++){
        btnArray[i]=new Button(this);
        layout.addView(btnArray[i],params);

    }
for(int i=0; i<n; i++)
{
   Button b = new Button(this);
   b.setId(i);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top