Search code examples
androidlambdaonclicklistenersnackbar

Cannot resolve Snackbar.make() in setOnclicklistener with lambda


I was trying to add Snackbar type message for my actions, When i used Snackbar it gives error cannot resolve make().

Snackbar.make(this,"Field should not be empty ",Snackbar.LENGTH_SHORT).show();

But this gives error

cannot resolve method 'make()'

After googling and checking on SO i found that it somehow works well with normal setOnclicklistener also i tried it and it worked well in setOnclicklistener of a fragment, But i am using setOnclicklistener with lambda expression that is why here i am pretty confused how to use snackbar because the default method giving error.

This is what i am doing

loginButton.setOnClickListener(view -> login());

And here's my login function

private void login() {

    setError();

    String email = loginUserName.getText().toString();
    String password = loginPassword.getText().toString();

    int err = 0;

    if (!validateEmail(email)) {

        err++;
        Snackbar.make(this,"Enter Valid fields",Snackbar.LENGTH_SHORT).show(); //here is the problem
        mTiEmail.setError("Email should be valid !");
    }

    if (!validateFields(password)) {

        err++;
        mTiPassword.setError("Password should not be empty !");
    }

    if (err == 0) {

        loginProcess(email,password);


    } else {

        Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
    }
}

I hope i am using snackbar correctly if not please let me and also tell why it gives error here Cannot resolve make()

Any suggestions or thoughts ?


Solution

  • You might call SnackBar.make() in Activity range. So this is Activity not View. You should change code like this SnackBar.make(loginButton,...).


    Update

    Compare to Toast, SnackBar is included in Activity. So, if you press Home button, Toast is still shown, but snackBar is hidden with the activity. Because, snackbar is used for showing message to users and interact with users too.

    In SnackBar codes in Android source, it finds the parent view group using view parameter. And Snackbar layout is included in the view group.