androidKotlin


Source link: https://github.com/yoavst/androidKotlin

Depracated - use Anko by jetbrains

Android Kotlin Extensions

A collection of Kotlin extensions for Android, based on KotlinAndroidLib and Android Kotlin Extensions.

Include this library in your project

Step 1. Add the JitPack repository to your build file

repositories {

maven {

 url "https://jitpack.io"

}
  
}

Step 2. Add the dependency in the form

dependencies {

 compile 'com.github.yoavst:androidKotlin:1.5.1'  
}

Activities & Services

Example: Start an Activity

Java

Intent intent = new Intent(this, SuperPowersActivity.class);
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);

Kotlin

val flags = flags(Intent.FLAG_ACTIVITY_NEW_TASK, Intent.FLAG_ACTIVITY_CLEAR_TOP) start<SuperPowersActivity>(flags)

Example: Create an Intent

Java

Intent intent = new Intent(this, SuperPowersActivity.class);

Kotlin

val intent = intent<SuperPowersActivity>()

Api

Java

int sdk = Build.VERSION.SDK_INT; if (sdk >= Build.VERSION_CODES.LOLLIPOP) {

}
 if (sdk < Build.VERSION_CODES.LOLLIPOP) {

}
 if (sdk >= Build.VERSION_CODES.KITKAT) {

}
 if (sdk < Build.VERSION_CODES.KITKAT) {

}
 if (sdk >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

}
 if (sdk < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

}
 if (sdk >= X) {

}
 if (sdk < X) {

}

Kotlin

val sdk = currentVersion() if (lollipopOrNewer()) {

}
 if (beforeLollipop()) {

}
 if (kitkatOrNewer()) {

}
 if (beforeKitkat()) {

}
 if (icsOrNewer()) {

}
 if (beforeIcs()) {

}
 if (versionOrNewer(x)) {

}
 if (beforeVersion(x)) {

}

Async and main thread

Kotlin

async {
  
}
  mainThread {
  
}

Broadcast Receiver

Java

new BroadcastReceiver() {

 @Override
 public void onReceive(Context context,Intent intent) {

 
}

}
;

Kotlin

broadcastReceiver {
 context,intent -> 
}

Layout Inflation

Java

LayoutInflater layoutInflater = LayoutInflater.from(this);
 View awesomeView = layoutInflater.inflate(R.layout.my_awesome_layout, null);

Kotlin

val awesomeView = inflateLayout(R.layout.my_awesome_layout)

Logs

Example: Logging

Java

String tag = this.getClass().getName();
 Log.i(tag, "Howdy! Info");
 Log.d(tag, "Knock knock! Debug");
 Log.e(tag, "Grim, Error");
 Log.wtf(tag, "Damn! WTF");
 // Nope, not what you think. Refer the docs :P

Kotlin

i("Howdy! Info") d("Knock knock! Debug") e("Grim, Error") wtf("Damn! WTF")

Preferences

Example: Single Preference

Java

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
 Editor editor = preferences.edit();
 editor.putBoolean("KEY_WALKTHROUGH_COMPLETE", complete);
 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {

editor.commit();
 
}
 else {

editor.apply();
 
}

Kotlin

getDefaultSharedPreferences().putBoolean("KEY_WALKTHROUGH_COMPLETE", complete)

Example: Bulk Preferences

Kotlin

getDefaultSharedPreferences()
.bulk()
.putBoolean("KEY_WALKTHROUGH_COMPLETE", complete)
.putString("KEY_LAST_USED", lastUsedIso8601Date)
.applyBulk()

Toasts

Example: Short Message

Java

Toast.makeText(this, R.string.welcome, Toast.LENGTH_SHORT).show();

Kotlin

toast(R.string.welcome)

Example: Long Message

Java

Toast.makeText(this, R.string.welcome, Toast.LENGTH_LONG).show();

Kotlin

longToast(R.string.welcome)

System Services

Example: System service on code

Java

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

Kotlin

val alarmManager = context.alarmManager() val notificationManager = context.notificationManager()

Example: System service field (lazy)

Java

AlarmManager alarmManager; NotificationManager notificationManager; public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 
}

Kotlin

val alarmManager: AlarmManager by systemService() val notificationManager: NotificationManager by systemService()

Resources

Example: Typeface from Assets

Java

AssetManager assetManager = getAssets();
 Typeface sourceSansPro = Typeface.createFromAsset(assetManager, "fonts/source-sans-pro.ttf");

Kotlin

val sourceSansPro = typefaceFromAssets("fonts/source-sans-pro.ttf")

Example: Get resources

Java

int number = getResources().getInteger(R.integer.number);
 int dimenPixelSize = getResources().getDimensionPixelSize(R.dimen.size);
 int color = getResources().getColor(R.color.red);
 int[] intArray = getResources().getIntArray(R.array.ids);
 String[] stringArray = getResources().getColor(R.array.options);
 Drawable drawable = getResources().getDrawable(R.drawable.background);

Kotlin

val number = intRes(R.integer.number) val dimenPixelSize = dimenRes(R.dimen.size) val color = colorRes(R.color.red) val intArray = intArrayRes(R.array.ids) val stringArray = stringArrayRes(R.array.options) val drawable = drawableRes(R.drawable.background)

Example: Get resources as field (lazy)

Kotlin

val text by stringResource(R.string.text) val number by intResource(R.integer.number) val dimenPixelSize by dimenResource(R.dimen.size) val color by colorResource(R.color.red) val intArray by intArrayResource(R.array.ids) val stringArray by stringArrayResource(R.array.options) val drawable by drawableResource(R.drawable.background)

Example: DP and PX converter

Kotlin

val px = 40.toPx(context) val dp = 180.toDp(activity)

More...

More extensions under development.

License

Copyright 2015 Yoav sternberg  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

A custom view that gives the user a look and feel of selecting options with smoother slider animation.

With this SDK you can access the API behind the DRAE (Diccionario de la Real Academia Española, the official spanish dictionary) in order to use it in your own app.

Shortify is used for minimizing your coding effort in your development environment. It has some builtin method and classes which helps you in creating mostly used element and tasks in Android app.

Android library handling flashlight for camera and camera2 api. Added support for handling display/screen light.

Yet Another Android animated Seekbar inspired from Philips Hue app.

Great sound quality, audio cleanliness and very smooth interface. Playing the folder structure, artist or album or create your own playlists with local or online tracks.

  • 10-band equalizer
  • Themes
  • mp3, flac, aac, ogg, oga, m4a, m4b, m4p, wma and other audio formats

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes