Android: How to callback from a library to the main app project?

Viewed 527

i have a main app named App_1 then a custom library Lib_1

Project View

how can i callback or run a method from the app_1 Main Activity when i clicked a button in lib_1? tia.

3 Answers

From what you have described, there is one main concept you need to learn first:

  • the library is the dependency of the app

To set it up, add library to in build.gradle file of your app (find it in your app folder) in dependencies section - it may look like that:

dependencies {
  implementation project( ':library' )

  //other dependencies below (order doesn't really matter)
  (...)
}

Then there are a few things which needs a little bit more explanation - what do you mean by "button from library"? Have you created a custom button (check official documentation to check what it is)? Or do you mean that clicking a button in your app will run a function from library?

Create an interface in lib_1, then in app_1 create implementation of that interface and pass it to lib_1, whenever a button in lib_1 is clicked call a method form that interface.

Your app_1 can access lib_1's code(if you have setup the right relationship for the 2 modules), so you can define a callback method in your lib_1. e.g. public void onLibButtonClick(OnClickListener listenerFromApp). When you click the button on lib_1, you can call listenerFromApp.onClick(View) to transfer click event.

You can also use LocalBroadcastManager related api to transfer event between modules(in one application). This should be reasonable sometime.

Related