allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.andob:DobDroidMiscUtils:v1.0.7'
}
- ToolbarX
- BottomNavigationViewX
- ViewPagerX
- EditTextX
- ScreenSize
- PermissionsHandler
- Keyboard
- FileManager
- RetrofitX
- CacheDelegate
- Async
- Library dependencies
Toolbar eXtension methods. To setup a toolbar with back button:
toolbar.setupBackIcon()
Toolbar with menu on the right:
toolbar.setMenu(R.menu.menu_main)
toolbar[R.id.add] = {
Log.e("a", "add logic")
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<item
android:id="@+id/add"
android:title="Add"
app:showAsAction="always" />
</menu>
If you are using menu or back button, override:
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
toolbar.onCreateOptionsMenu(menuInflater, menu)
return super.onCreateOptionsMenu(menu)
}
If you are using menu, override:
override fun onOptionsItemSelected(item: MenuItem?) : Boolean
{
toolbar.onOptionsItemSelected(item)
return super.onOptionsItemSelected(item)
}
Toolbar with hamburger menu icon: Please import this library.
implementation 'com.balysv.materialmenu:material-menu:2.0.0'
toolbar.setupHamburgerMenu()
toolbar.setOnHamburgerMenuClickedListener {
Log.e("a", "toggle drawer")
}
BottomNavigationView eXtension method
bottomNavigationView.setupWithViewPager(viewPager)
bottomNavigationView.setupWithViewPager(viewPager, initialTab = 0)
ViewPager eXtension method
viewPager.setOnPageChangedListener { page ->
Log.e("a", "You're on page $page")
}
EditText eXtension methods
editText.setOnTextChangedListener { newText ->
Log.e("a", newText)
}
editText.setOnEditorActionListener { actionId ->
if (actionId==EditorInfo.IME_ACTION_DONE)
Log.e("a", "enter pressed")
}
Used to get the width, height and density of the screen. In Application Class onCreate
method:
ScreenSize.init(withContext = this)
Then, you can simply use the properties from ScreenSize
:
if (ScreenSize.width<ScreenSize.height)
if (ScreenSize.density>=2.0) {...code...}
Used to ask for dangerous permisssions. In the Activity class:
class MainActivity : AppCompatActivity()
{
val permissionsHandler = PermissionsHandler()
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsHandler.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
To ask for permissions, simply use:
permissionsHandler.askFor(arrayOf(Manifest.permission.CAMERA))
.onGranted { Log.e("a", "YAY") }
.onDenied { Log.e("a", "NAY") }
.withContext(context = this)
Used to open or close the keyboard
Keyboard.open(on = context)
Keyboard.close(on = context)
Extend FileManager
class to create classes that manages app file's paths. For instance, getSampleFilePath
will return /storage/emulated/0/Dob/sample.pdf
object AppFileManager : FileManager()
{
override fun folderBasePath() : String = Environment.getExternalStorageDirectory().absolutePath
override fun folderName() : String = "Dob"
fun getSampleFilePath() : String = getFilePath("sample.pdf")
}
Download and upload files:
interface IApiClient
{
@Streaming
@GET("/samples/pdf.pdf")
fun downloadPdf() : Call<ResponseBody>
@Multipart
@POST("/samples/pdf.pdf")
fun uploadPdf(@Part file : MultipartBody.Part) : Call<Unit?>
}
To download a file:
ApiClient.Instance.downloadPdf().enqueue(object : Callback<ResponseBody>
{
override fun onFailure(call: Call<ResponseBody>, t: Throwable)
{
Log.e("a", "fail")
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>)
{
Thread {
try
{
downloadFile(response.body()!!, outputPath = AppFileManager.getSampleFilePath())
Log.e("a", "success")
}
catch (ex : Exception)
{
Log.e("a", "fail")
}
}.start()
}
})
To upload a file:
ApiClient.Instance.uploadPdf(fileUpload(context = this, path = AppFileManager.getSampleFilePath()))
.enqueue(object : Callback<Unit?>
{
override fun onFailure(call: Call<Unit?>, t: Throwable)
{
Log.e("a", "fail")
}
override fun onResponse(call: Call<Unit?>, response: Response<Unit?>)
{
Log.e("a", "success")
}
})
Use by cache()
delegate to cache in memory values returned by other delegates. For instance, with kotpref library:
object Preferences : KotprefModel()
{
var username by cached(stringPref())
var level by cached(intPref())
var firstRun by booleanPref(default = true)
}
Username will be returned from memory cache. If not found in cache, it will be fetched by stringPref
delegate, from SharedPreferences
.
In Application onCreate,
Run.handler=Handler(mainLooper)
To run on UI thread:
Run.onUIThread {
println("on ui thread")
}
To run delayed on UI thread:
Run.delayed(1000) {
println("delayed")
}
To run async on a new thread:
Run.async {
println("on new thread")
}
To run async and return a result, handling success and error cases (promises style). onAny
will alwats be called before onSuccess
or onError
. Callback methods are run on UI thread
Run.async(task = {
println("on new thread with result")
Thread.sleep(1000)
return@async 1
},
onAny = { println("hide loading dialog") },
onError = { it.printStackTrace() },
onSuccess = { println("result: $it") })
To run async without a result, handing success:
Run.async(task = {
println("on new thread without result")
Thread.sleep(1000)
},
onSuccess = { println("done!") })
To run lambdas in paralel. onDone
is called after all tasks are done. onError
is called after a task throws exception. If a task has an error, remaining tasks will not be executed anymore. Specify maximumNumberOfThreads = value
argument to set the maximum amount of paralel running threads at a given time. Default value is 4
Run.paralel(tasks = mutableListOf(
{
println("task 1")
},
{
println("task 2")
},
{
println("task 3")
}), onDone = {
println("Done!")
}, onError = {
println("Exception: $it")
})
To set a global error handler for paralel
and async
methods:
Run.globalErrorHandler={ ex ->
ex.printStackTrace()
}
This library depends on the following libraries:
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.balysv.materialmenu:material-menu:2.0.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
You can exclude any of those:
implementation ('com.github.andob:DobDroidMiscUtils:v1.0.7') {
exclude group: 'com.android.support'
exclude group: 'com.balysv.materialmenu'
exclude group: 'com.squareup.okhttp3'
}
Copyright 2019 Andrei Dobrescu
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.`