Adegbola bolu Adegbola bolu - 1 year ago 98
Android Question

How to click/use dynamically created buttons in android

I dynamically created 3 buttons, but I can't access these buttons via the

My code is below:

quesButton = new Button[3];

ll1 = (LinearLayout) findViewById(;

for(int x=0; x<3; x++){
quesButton[x] = new Button(MainActivity.this);
quesButton[x].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
quesButton[x].setText("Q" + (x + 1));


Answer Source

You have to attach an onClickListener AFTER your create a new element.

quesButton[x] = new Button(MainActivity.this);
quesButton[x].setOnClickListener(new OnClickListener() 
    public void onClick(View v) 
        // Your code that you want to execute on this button click
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download