1

My program dynamically creates a button when a user enters their name.

            changeButton = new Button(getApplicationContext());

            changeButton.setText("Change");
            changeButton.setId(R.id.buttonOne);

I created the id in a my res/values folder. I would like to now set an OnClickListener() for this button but am not sure how to reach it? Normally I would create a Button object and have it point to my Button widget in my XML file (findViewById(R.id.whateverButtonItIs). In this case, since it was created dynamically,there's nothing in the XML file to point to so I'm not sure how to make it work. Please help. Thank you.

2
  • 1
    you already have an instance of the button, since you assigned it to variable changeButton . Use simply changeButton.setOnClicklistener(yourListener); Commented Aug 21, 2015 at 11:41
  • way is same, either you have created it from xml or dynamic. Commented Aug 21, 2015 at 11:42

1 Answer 1

2

try this:

LinearLayout ll = (LinearLayout)findViewById(R.id.layout);

        Button btn = new Button(this);
        btn.setText("Manual Add");
        btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        ll.addView(btn);
     btn .setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


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