0

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]);
    }
3
  • Where you are adding the setOnClickListener in these buttons ? Commented Sep 2, 2016 at 12:29
  • From what you've shown us, you never even use setOnClickListener... Share the rest of the relevant code please. Commented Sep 2, 2016 at 12:36
  • I was trying to apply setOnclickListener outside the code above, but Tom Nijs answer has solved it. Thanks. Commented Sep 2, 2016 at 12:43

1 Answer 1

2

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
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.