Search code examples
androidkotlininterface

Creating common code for Interface method for multiple activities - Android (Kotlin)


I have an interface which has two methods to override.

There are two activities with different UI and both needs same functionality to override the methods of that Interface.

Now, I can do implement that Interface in my both the activities and can also override the methods in both the activities.

But I don't want to make my code duplicate. Is there any common way to make my overridden method common so that I need not to write the same code again?

In short, I want to write Interface implementation code only once which will be used by two separate activities. Please suggest.


Solution

  • So you can just create a base activity class and implement this interface and in the another activities you may extend this base class, and if you need, override both. But i don't recommend it, because following the best practices is better avoid create new rules in your code, a while will get hardest to understand. But the better approach is review you architecture, maybe you can just have one activity and a fragment, and share a viewModel between both.