Reputation: 7370
I'm trying to add some buttons at runtime and want to assign an OnClickListener that triggers the start of a new activity.
But I get a The constructor Intent(new View.OnClickListener(){}, Class<CollectionDemoActivity>) is undefined
error in my IDE Editor.
While startActivity(new Intent(this,CollectionDemoActivity.class));
is accepted from the IDE and works fine when I call it from e.g. the onStart()
Method
But I need the buttons dynamically created..... What am I doing wrong? What is the the best alternative for this?
final LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
for (int i = 1; i <= 10; i++) {
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("_button " + id_);
btn.setBackgroundColor(Color.GREEN);
ll.addView(btn, params);
Button btn1 = ((Button) ll.findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(this,CollectionDemoActivity.class));
}
});
Upvotes: 0
Views: 241
Reputation: 10977
this
inside the anonymous OnClickListener
refers to to exactly this surrounding class, not to the Activity
. Assuming the Activities name is MyActivity
, change this
to MyActivity.this
or getContext()
Upvotes: 1