I wrote the following code but am not getting how to write OnclickListner()
method for all buttons.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.ll1Relative);
for (int i = 1; i < 10; i++) {
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
Button b = new Button(this);
b.setText(""+ i);
b.setId(100+i);
b.setWidth(30);
b.setHeight(20);
layout.addView(b, p);
}
}
You can use an anonymous inner method like this:
Button b = new Button(this);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
b.setText("" + i);
b.setTag("button" + i);
b.setWidth(30);
b.setHeight(20);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With