Adegbola bolu Adegbola bolu - 3 months ago 10
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

setOnClicklistener
method.
My code is below:

quesButton = new Button[3];


ll1 = (LinearLayout) findViewById(R.id.ll4button);

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));

ll1.addView(quesButton[x]);
}

Answer

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

quesButton[x] = new Button(MainActivity.this);
...
quesButton[x].setOnClickListener(new OnClickListener() 
{ 
    @Override
    public void onClick(View v) 
    {
        // Your code that you want to execute on this button click
    }
});
Comments