简体   繁体   中英

Buttons created on runtime how to set on clicklistener for each?

I am creating buttons based on the array size given. My problem is how do I make an onclicklistener when a button is pressed all other buttons change their background colour.

Eg: 3 buttons are present. when button1 is pressed Button 2 and 3 change their background colour. here is my code:

for( j = 0; j < arrayName.length; j++) {
    //create the button
    final Button btn = new Button(this);

    //set all your button attributes, like text color,background color etc. here
    btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    btn.setText(arrayName[j]);
    btn.setId(j);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Toast.makeText(ProductPage.this,btn.getText().toString(),Toast.LENGTH_SHORT).show();
        }
    });
    //add the button to your linear layout
    buttonLayout.addView(btn);
}

You can achieve as below

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

implement common onclick listener

 @Override
public void onClick(View v) {

    for(int i = 0 ; i < buttonLayout.getChildCount() ; i++){
        View buton = buttonLayout.getChildAt(i);
        buton.setBackground();
    }
}

Set same listener for all button

for (int j = 0; j < arrayName.length; j++) {
            //create the button
            final Button btn = new Button(this);

            //set all your button attributes, like text color,background color etc. here
            btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            btn.setText(arrayName[j]);
            btn.setId(j);
            btn.setOnClickListener(this);
            //add the button to your linear layout
            buttonLayout.addView(btn);
        }

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