简体   繁体   English

Android:如何从库回调到主应用程序项目?

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

i have a main app named App_1 then a custom library Lib_1我有一个名为 App_1 的主应用程序,然后是一个自定义库 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 ?当我单击lib_1中的按钮时,如何从app_1主活动回调或运行方法? tia.蒂亚。

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项部分的应用程序的 build.gradle 文件中添加library (在您的应用程序文件夹中找到它) - 它可能如下所示:

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 (checkofficial documentation to check what it is)?您是否创建了自定义按钮(查看官方文档以检查它是什么)? Or do you mean that clicking a button in your app will run a function from library?还是您的意思是单击应用程序中的按钮将从库中运行 function?

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.lib_1中创建一个接口,然后在app_1中创建该接口的实现并将其传递给lib_1 ,每当单击lib_1中的按钮时,都会调用该接口的方法。

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.您的 app_1 可以访问 lib_1 的代码(如果您为 2 个模块设置了正确的关系),因此您可以在 lib_1 中定义回调方法。 eg public void onLibButtonClick(OnClickListener listenerFromApp) .例如public void onLibButtonClick(OnClickListener listenerFromApp) When you click the button on lib_1, you can call listenerFromApp.onClick(View) to transfer click event.当你点击lib_1上的按钮时,你可以调用listenerFromApp.onClick(View)来传递点击事件。

You can also use LocalBroadcastManager related api to transfer event between modules(in one application).您还可以使用LocalBroadcastManager相关的 api 在模块之间传输事件(在一个应用程序中)。 This should be reasonable sometime.这在某个时候应该是合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM