5

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?

someonewithpc
  • 366
  • 5
  • 14

4 Answers4

15

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

Hamid Sj
  • 983
  • 7
  • 19
3

Thanks to @HamidSj's comment, I noticed I wasn't calling setContentView(binding.getRoot()), but instead setContentView(R.layout.activity_login).

Using binding.getRoot() fixed the issue, but I'm not sure why

someonewithpc
  • 366
  • 5
  • 14
2

Initialising binding after setting setContentView will prevent binding initialisation and views binding correctly.

You need to initialise binding first and then setting content view with: setContentView(binding.getRoot()).

mmmatey
  • 666
  • 8
  • 15
1

Call setContentView after inflating.

public class Login extends BaseClassFragmentActivity {
        ActivityLoginBinding binding;
        private final String TAG = "[LOGIN]";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(binding.getRoot());
    
            binding = ActivityLoginBinding.inflate(getLayoutInflater());
            View view = binding.getRoot();
            setContentView(view);
        }
    }

As you are using id btn_login, use setOnClickListener as

binding.btnLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.v(TAG, "View Binding press");
                }
            });
Amar Gore
  • 909
  • 8
  • 9