Android Remove arguments to match “intent()”

后端 未结 2 2014
一整个雨季
一整个雨季 2021-01-20 20:42

I am trying to start a second activity but I am getting an error on the code.

import android.os.Bundle;
import android.content.Intent;
import android.app.Act         


        
2条回答
  •  一整个雨季
    2021-01-20 21:18

    In Java, this refers to the current instance of the class containing the code.

    Here

     mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
            @Override
            public void onItemClick(QuickAction quickAction, int pos, int actionId) {
                ActionItem actionItem = quickAction.getActionItem(pos);
    
                if (actionId == ID_SPLASH) {
                    Intent intent = new Intent(this, SplashActivity.class);
                    startActivity(intent);
    

    you are creating the intent inside onItemClick which is a method of an instance of the class OnActionItemClickListener. This is known as an "anonymous inner class". Anonymous because it has no name (unlike public class MyClass) and inner because it exists only inside the class instance declaring it.

    this therefore refers to the instance of the click listener.

    Instead, use the instance of the outer class - your Activity.

    Intent intent = new Intent(MainActivity.this, SplashActivity.class);
    

    Another way of thinking about this is that the constructor for Intent that you are using expects a Context as the first parameter.

    From the docs:

    Intent(Context packageContext, Class cls) Create an intent for a specific component.

    Since Activity extends Context, your activity is an instance of Context. OnActionItemClickListener is a class so the compiler will generate a compile time error.

提交回复
热议问题