要在您的项目中创建新的库模块,请执行以下操作:
Click File > New > New Module.
In the Create New Module window that appears, click Android Library, then click Next.
There's also an option to create a Java Library, which builds a traditional JAR file. While a JAR file is useful for many projects— especially when you want to share code with other platforms—it does not allow you to include Android resources or manifest files, which is very useful for code reuse in Android projects. So this guide focuses on creating Android libraries.
Give your library a name and select a minimum SDK version for the code in the library, then click Finish.
Gradle 项目同步完成后,库模块会出现在左侧的“项目”面板中。如果您没有看到新的模块文件夹,请确保它显示的是 Android 视图。
在这里更深入地了解https://developer.android.com/studio/projects/android-library
//编辑
创建项目
创建新项目
基本活动
下一个
名称:HelloWorld
包名:com.test.helloworld
API:16
语言:JAVA
更改了 activity_main.xml 以显示居中文本
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World"
android:textSize="25sp" />
</RelativeLayout>
创建库模块
文件/新/新模块
安卓库
下一个
模块名称:库
开发工具包:16
语言:JAVA
完成
Gradle 正在自动同步
创建测试类
我知道我可以将此字符串设为静态,但 OP 请求了一个方法
请注意,我不小心在模块的测试包内创建了类。无法访问
package com.test.library;
public class Library {
public static String getDisplayText(){
return "it worked";
}
}
将我的库添加到主项目
转到 settings.gradle 并确保它首先包含您的模块
包括“:图书馆”
包括 ':app'
这已经为我完成了
移到 app 模块的 build.gradle 并添加
在依赖项的顶部包含 project(":library")
我必须手动执行此操作
现在与 gradle 重新同步
访问课程
这是我的 MainActivity.java
package com.test.helloworld;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import com.test.library.Library;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView simpleTextView = (TextView) findViewById(R.id.simpleTextView);
simpleTextView.setText(Library.getDisplayText());
}
}
它就像一个魅力。希望我能帮助你。会很高兴赞成投票