The following is my situation:
I have a library project and a project based on it. Now in the library I have two classes A and B, whereby A uses B. In the project using the library, I have another class B, which should override the class B from the library.
But every time class A makes a call, it ends up in the class B from the library. How can I tell Android that class B from my project should be used INSTEAD of class B from the library?
I dont know if this is the best way to do it but i do it this way;
I create a class A from the project and this class extends form the library project
public class A extends libraryProject_A{
//here i put all methods from the new class B to override methods from library class B
}
That does not work with the current layout. You have to use the strategy pattern. In your library define LibA with a constructor that takes a object of type LibB in the constructor:
class LibA{
LibB b;
public LibA(LibB b)
this.b = b;
}
}
Then you can override LibB in your project and create LibA with the class that extends LibB:
class ProjectB extends LibB{
}
LibA a = new LibA(new ProjectB());
Answer to Turbos question:
You want to start Project-Activities from your Library. So then move the code that creates the Intent
into your Projects, because only in your project you know the type or name of the Activity
to be started.
The solution you mentioned in your comment (here) creates the Intent
in the library project, by guessing the name of the Activity
that should be started. There is nothing really wrong with that but it's not an elegant solution. You can only start Activities
that follow that special naming scheme. And because of that you cannot start arbitrary Activities
that are visible in your projects like Activities
from other libraries, where you cannot change the name of the class.
To move the Intent
creation into your libraries you can i.e. use the strategy, template or factory-method pattern. See Design Patterns on Wikipedia for even more (creational) patterns that match your library design.
A simple solution would be:
Create an abstract LibraryActivity
and extend your ProjectActivities from it. The LibraryActivity
defines an abstract method that returns the Intent
. The implementation of that abstract method is done in your ProjectActivities
.
abstract class LibActivity{
private void doSomething(){
//Library does something
//and finally calls createIntent() to start an project specific Activity
startActivity(this.createIntent());
}
protected abstract Intent createIntent();
}
class ProjectActivity extends LibActivity{
protected Intent createIntent(){
return new Intent(ProjectActivity.this, AnyActivityYouWant.class);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With