简体   繁体   中英

why am i getting error when trying to open new activity in android studio

错误

I'm getting this error when I write the intent inside the onCreate method. But when I write the intent inside an outer method and call it, it works.

在职的

Button click listener is an interface and you implemented it here as an anonymous class, so inside of that class this refers to that anonymous class, not your activity class, but Intent constructor needs activity class implementation, therefore as @ADITYA RANADE answered you need to change it to MainActivity.this .

However if you replace anonymous class with lambda you can avoid this:

    Button button = new Button(context);
    button.setOnClickListener(v -> {
        Intent intent = new Intent(this, MainActivity.class);
    });

在 Intent 中将其更改为MainActivity.this

Well that is because of the place or more precisely "context" (not the androidish Context) of where you are calling it.

When you call it from the anonymously created inner class which implements the listener for a view click, so in this case the this represents something else - anonymous class.

But on the other side when you make the method eg openScheduleActivity() inside the activity itself, the this keyword represents the activity itself and in fact represents the androidish Context or in this particular case even the activity. So you can either stay with case that you have already had there and slightly edit it, or you can use lambda expression, or you can use the method inside the activity itself as you have already discovered.

edited case:

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, schedule.class);
                startActivity(intent);
            }
        });

lambda expression:

        button.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, schedule.class);
            startActivity(intent);
        });

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