The constructor Intent(new View.OnClickListener(){

2019-04-04 06:30发布

I am getting the following error:

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

In the following code snippet:

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

}

What am I doing wrong with the line:

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

3条回答
Root(大扎)
2楼-- · 2019-04-04 07:20

change

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

to

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

it worked for me.

查看更多
家丑人穷心不美
3楼-- · 2019-04-04 07:22

Just a few lines to explain the reason why "this" does not work in:

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

The intent is created inside an other class, here an anonymous inner class OnClickListener. Thus "this" does not refer the instance of your Activity (or Context) as intended but the instance of your anonymous inner class OnClickListener.

As @Falmarri mentions in his answer instead of "this" you need to use your Activity name followed by ".this" to point to the right instance:

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

查看更多
三岁会撩人
4楼-- · 2019-04-04 07:26

Change

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

to

final Intent i = new Intent(Screen2.this, DrinksTwitter.class)
查看更多
登录 后发表回答