Skip to content
Advertisement

Is it mandatory to create inner classes to handle events in DataBinding?

I was learning about DataBinding, particularly the section about handling events and click events. Now, I noticed in a few YouTube tutorials that I instructors were mainly using an inner class to handle these events. However, earlier, I’d written this code that implemented the View.OnClickListener and directly allowed me to handle click events.

Here it is:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    private ActivityMainBinding activityMainBinding;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        activityMainBinding.enterButton.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {
        if (view == activityMainBinding.enterButton) {
            String name = activityMainBinding.nameEditText.getText().toString();
            String email = activityMainBinding.emailEditText.getText().toString();
            String country = activityMainBinding.countryEditText.getText().toString();
 
            User user = new User(name, email, country);
            activityMainBinding.setUser(user);
        }
    }
}

And this works.

I was wondering, is this form of handling click events not considered a good practice? I checked through a few more tutorials and they all used inner classes, thereby causing this doubt.

Thanks for any help.

Advertisement

Answer

Q: Is it necessary to create inner classes?

A: No, absolutely not. It’s merely a useful convention 🙂

Q: Is this form of handling click events … a good practice?

A: In general, any individual “class” should do “one thing”. The class’s properties and its methods should match the class’s “abstraction”.

For example, an “Automobile” class should probably not have an “onClick()” method. Even if your “Automobile” class implementation might have a “button”, with an “onClick()” method.

Or your “Automobile” might have a dozen different buttons. In that case, I’d definitely prefer to see a dozen anonymous inner classes, one for each button. It would be shorter; it would be cleaner.

In your example, however, I don’t see any problem. It looks fine 🙂

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement