简体   繁体   中英

Dynamically created onClickListener and start of a new activity

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM