Конструктор Intent (новый View.OnClickListener() {}, класс <DrinksTwitter>) - undefined

Я получаю следующую ошибку:

The constructor Intent(new View.OnClickListener(){}, 
                       Class<DrinksTwitter>) is undefined

В следующем фрагменте кода:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Get the EditText and Button References
    etUsername = (EditText)findViewById(R.id.username);
    etPassword = (EditText)findViewById(R.id.password);
    btnLogin = (Button)findViewById(R.id.login_button);
    btnSignUp = (Button)findViewById(R.id.signup_button);
    lblResult = (TextView)findViewById(R.id.result);

    // Set Click Listener
    btnLogin.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Check Login
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();


            if(username.equals("test") && password.equals("test")){
                final Intent i = new Intent(this, DrinksTwitter.class);  //error on this line
                startActivity(i);
                // lblResult.setText("Login successful.");
                } else {
                lblResult.setText("Invalid username or password.");
            }
        }
    });

    final Intent k = new Intent(Screen2.this, SignUp.class);

    btnSignUp.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            startActivity(k);
        }
    });

}

Что я делаю неправильно с линией:

final Intent i = new Intent(this, DrinksTwitter.class); 

Ответы

Ответ 1

Измените

final Intent i = new Intent(this, DrinksTwitter.class)

to

final Intent i = new Intent(Screen2.this, DrinksTwitter.class)

Ответ 2

Всего несколько строк, чтобы объяснить причину, по которой "this" не работает:

final Intent я = new Intent (это, DrinksTwitter.class)

Цель создается внутри другого класса, здесь анонимный внутренний класс OnClickListener. Таким образом, "this" не ссылается на экземпляр вашего действия (или контекста), как предполагалось, а на экземпляр вашего анонимного внутреннего класса OnClickListener.

Как заметил @Falmarri в своем ответе вместо "this", вам нужно использовать ваше имя Activity, за которым следует ".this", чтобы указать на правильный экземпляр:

окончательное намерение я = новый намерение (Screen2.this, DrinksTwitter.class)

Ответ 3

изменить

    final Intent i = new Intent(this, DrinksTwitter.class) 

to

    final Intent i = new Intent(getApplicationContext(), DrinksTwitter.class);

это сработало для меня.