Android Studio Version < 3.6:
For Windows:
File -> Settings ->Build, Execution,Deployment -> Build Tools -> Gradle
For Mac OS:
Preferences ->Build, Execution,Deployment -> Build Tools -> Gradle
Check/UnCheck Offline work
checkbox as per your need.
Android Studio Version >= 3.6:
follow steps in the image: