Search code examples
androidandroid-viewbinding

Android View Binding onClickListener not being called


I'm updating an app and I read that the recommended way to handle Views now is to use View Binding. I followed the instructions, however I'm having some problems:

Adding a click listener with the following works:

((LinearLayout) findViewById(R.id.btn_login)).setOnClickListener(v -> {
    Log.v(TAG, "findViewById press");
});

Whereas the following doesn't

binding.btn_login.setOnClickListener(v -> {
   Log.v(TAG, "View Binding press");
});

The docs say it should. I wanted to try this on a new project, to ensure it wasn't related to the app configuration in some way, but I get the same result - it doesn't work.

I'm initializing it like so:

public class Login extends BaseClassFragmentActivity {
    ActivityLoginBinding binding;
    private final String TAG = "[LOGIN]";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
    }
}

Am I doing something wrong?


Solution

  • Consider that you should use setContentView(binding.getRoot()); in your onCreate method.