Reputation: 1543
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.
Upvotes: 1
Views: 52
Reputation: 110
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) {
}});
Upvotes: 2