Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple buttons at runtime? + android

Tags:

android

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);
    }
}
like image 735
Pramod Avatar asked Nov 14 '22 00:11

Pramod


1 Answers

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);
like image 170
RoflcoptrException Avatar answered Dec 23 '22 02:12

RoflcoptrException