Where to add folder of classes in Android Studio?

2020-06-07 06:52发布

I want to set up classes in different folders than activities. Current folder structure:

-> APP
  -> Manifests
  -> Java
     -> com.test.testing
        -> classes
            auth.java
        home_activity
     -> libs

auth.java

package com.test.testing;
// error here: Package name ‘com.test.testing’ does not correspond to file path.
public class auth{

  public void auth(){}
}

Plus, I can't call this class in activity:

import classes.auth;

So I went to build gradle an this are my configurations:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.test.testing"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            java.srcDirs = ['src/main/java', 'java/', 'src/main/java/com/test/testing/classes']
            assets.srcDirs = ['src/main/assets', 'src/main/assets/']
        }
    }
}

Android Studio is a little bit confusing about folder structures, we have several options to chose and I have no clue what some of them do. In my case, I added the folder "classes" as "Java Folder". enter image description here

EDIT 1: The tip was to create a package instead of a folder. So I created the package and a new file inside of it. Automatically, android studio filled with this information the file auth.java;

package com.test.testing.classes;

public class auth {

}

What happens is that I'm still unable to import the class into the activities. Althought when I start typing (in the activity) import classes it appears as a documentation help but it doesn't have any object associated, that said:

import classes.auth; 

Gives error.

I went again to build Gradle file and it didn't add anything to the java.srcDirs:

 sourceSets {
        main {
            java.srcDirs = ['java/', 'src/main/java']
        }
    }

EDIT 2: The solution to the import problem was the string. Instead of

import classes.auth;

Should be:

import com.test.testing.classes.auth;

2条回答
够拽才男人
2楼-- · 2020-06-07 07:22

Select Package from the List above (in your snap shot)

查看更多
相关推荐>>
3楼-- · 2020-06-07 07:22

I think many people are confused about the file structure, here it is:

app
  |--> manifests
  |--> java
  |      |--> com.example.yourapp
  |      |                     |--> MainActivity.java
  |      |                     |--> YOUR_PACKAGE_FOLDER
  |      |
  |      |--> com.example.yourapp(android test)
  |      |--> com.example.yourapp(test)
  |
  |--> res

You can try File -> New -> Package, so that android studio will create the folder at the correct location.
(File -> New -> Java Class for classes)

查看更多
登录 后发表回答