[Android] Android Studio src, res 공용으로 사용하기
Android 환경에서 개발하면서 미리 짜놓은 소스파일과 리소스 파일을 공용으로 사용할 일이 많습니다.
Android Studio 에서 기존에 사용하던 소스 파일과 리소스 파일을 링크하여 사용하는 방법.
<!--[if !supportLists]-->1. <!--[endif]-->build.gradle 작성 (App 폴더 내)
Build.gradle
android {
sourceSets.main{
java.srcDirs += 'src/main/../../../../../../common/src/main/java'
//src 파일이 있는 디렉토리를 src/main을 붙여서 추가한다.
res.srcDirs = ['src/main/res', 'src/main/../../../../../../common/src/main/res']
//res 파일이 있는 디렉토리를 src/main을 붙여서 추가한다.
}}
java.srcDirs는 java의 소스디렉토리에 상대경로로 지정한 소스파일을 추가한다는 의미이다. 다시 말하면 프로젝트의 src/main/java에 상대경로로 지정한 common폴더에 있는 src 파일을 링크하는 방법이다.
res.srcDirs는 대괄호로 묶여있는 경로에 있는 res파일을 res폴더에 링크시키는 내용이다.
2. 다음과 같은 폴더에 링크한 src 파일과 res 파일이 보임
<!--[if !supportLineBreakNewLine]-->
3. <!--[endif]-->주의 사항
R.id 등 프로젝트에 의존적인 리소스 파일이 src 파일에 포함되어 있으면 에러가 발생한다.
따라서 R.id, R.layout 과 같은 리소스 링크는 문자열로 갖고 와야한다.
resource link code
//context.getResources().getIdentifier("파일명", "디렉토리명", "패키지명")
context.getResources().getIdentifier("popup_dialog", "layout", context.getPackageName());
context.getResources().getIdentifier("dialogTitle", "id", context.getPackageName());
ex)
setContentView(context.getResources().getIdentifier("popup_dialog", "layout", context.getPackageName()));
findViewById(context.getResources().getIdentifier("dialogTitle", "id", context.getPackageName()));
<!--[endif]-->