├── .gitignore
├── .idea
├── .gitignore
├── AndroidProjectSystem.xml
├── appInsightsSettings.xml
├── codeStyles
│ ├── Project.xml
│ └── codeStyleConfig.xml
├── compiler.xml
├── deploymentTargetDropDown.xml
├── deploymentTargetSelector.xml
├── gradle.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── jarRepositories.xml
├── kotlinc.xml
├── migrations.xml
├── misc.xml
├── runConfigurations.xml
└── vcs.xml
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── lb
│ │ └── common_utils
│ │ └── sample
│ │ └── MainActivity.kt
│ └── res
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable
│ └── ic_launcher_background.xml
│ ├── layout
│ ├── activity_main.xml
│ └── content_main.xml
│ ├── menu
│ └── menu_main.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-mdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── values-land
│ └── dimens.xml
│ ├── values-night
│ └── themes.xml
│ ├── values-w1240dp
│ └── dimens.xml
│ ├── values-w600dp
│ └── dimens.xml
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── themes.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── library
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── jitpack.yml
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── lb
│ └── common_utils
│ ├── AdmobTestAdUnitIds.kt
│ ├── BaseViewModel.kt
│ ├── BundleEx.kt
│ ├── CollectionUtil.kt
│ ├── DialogFragmentCompatEx.kt
│ ├── EmptyActivityLifecycleCallbacksEx.kt
│ ├── FragmentViewBindingDelegate.kt
│ ├── PreferenceUtil.kt
│ ├── SpanFormatter.kt
│ ├── StatefulData.kt
│ ├── StringsUtil.kt
│ ├── SystemProperties.kt
│ ├── SystemUtils.kt
│ ├── ViewUtils.kt
│ ├── WorkerManagerUtils.kt
│ ├── custom_views
│ ├── CheckBox.kt
│ ├── GridLayoutManagerEx.kt
│ ├── LinearLayoutManagerEx.kt
│ └── WebViewContainer.kt
│ └── toast
│ ├── SafeToastContext.kt
│ └── ToastCompat.kt
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/AndroidProjectSystem.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/appInsightsSettings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 | xmlns:android
40 |
41 | ^$
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | xmlns:.*
51 |
52 | ^$
53 |
54 |
55 | BY_NAME
56 |
57 |
58 |
59 |
60 |
61 |
62 | .*:id
63 |
64 | http://schemas.android.com/apk/res/android
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 | .*:name
74 |
75 | http://schemas.android.com/apk/res/android
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | name
85 |
86 | ^$
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 | style
96 |
97 | ^$
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | .*
107 |
108 | ^$
109 |
110 |
111 | BY_NAME
112 |
113 |
114 |
115 |
116 |
117 |
118 | .*
119 |
120 | http://schemas.android.com/apk/res/android
121 |
122 |
123 | ANDROID_ATTRIBUTE_ORDER
124 |
125 |
126 |
127 |
128 |
129 |
130 | .*
131 |
132 | .*
133 |
134 |
135 | BY_NAME
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetDropDown.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetSelector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/migrations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CommonUtils
2 | Just a set of Android classes and functions that I commonly use in various projects.
3 |
4 | To use, add this:
5 |
6 | https://jitpack.io/#AndroidDeveloperLB/CommonUtils
7 |
8 | Some classes are based on solutions from:
9 |
10 | https://github.com/PureWriter/ToastCompat
11 |
12 | https://github.com/george-steel/android-utils/blob/master/src/org/oshkimaadziig/george/androidutils/SpanFormatter.java
13 |
14 | https://issuetracker.google.com/issues/115575872
15 |
16 | https://commonsware.com/blog/2018/11/24/workmanager-app-widgets-side-effects.html
17 |
18 | https://stackoverflow.com/a/21505193/878126
19 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | compileSdk 35
8 |
9 | defaultConfig {
10 | applicationId "com.lb.commonutils.sample"
11 | minSdk 21
12 | targetSdk 35
13 | versionCode 1
14 | versionName "1.0"
15 | multiDexEnabled true
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 | compileOptions {
25 | sourceCompatibility JavaVersion.VERSION_17
26 | targetCompatibility JavaVersion.VERSION_17
27 | }
28 | kotlinOptions {
29 | jvmTarget = "17"
30 | }
31 | buildFeatures {
32 | viewBinding true
33 | buildConfig = false
34 | }
35 | namespace 'com.lb.common_utils.sample'
36 | }
37 |
38 | dependencies {
39 | implementation 'androidx.core:core-ktx:1.15.0'
40 | implementation 'com.google.android.material:material:1.12.0'
41 | implementation 'androidx.constraintlayout:constraintlayout:2.2.0'
42 | implementation 'androidx.navigation:navigation-fragment-ktx:2.8.6'
43 | implementation 'androidx.navigation:navigation-ui-ktx:2.8.6'
44 | implementation project(':library')
45 | }
46 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/lb/common_utils/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils.sample
2 |
3 | import android.os.Bundle
4 | import android.view.Menu
5 | import android.view.MenuItem
6 | import androidx.appcompat.app.AppCompatActivity
7 | import com.lb.common_utils.sample.databinding.ActivityMainBinding
8 |
9 | class MainActivity : AppCompatActivity() {
10 | private lateinit var binding: ActivityMainBinding
11 |
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 | binding = ActivityMainBinding.inflate(layoutInflater)
15 | setContentView(binding.root)
16 | setSupportActionBar(binding.toolbar)
17 | }
18 |
19 | override fun onCreateOptionsMenu(menu: Menu): Boolean {
20 | // Inflate the menu; this adds items to the action bar if it is present.
21 | menuInflater.inflate(R.menu.menu_main, menu)
22 | return true
23 | }
24 |
25 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
26 | // Handle action bar item clicks here. The action bar will
27 | // automatically handle clicks on the Home/Up button, so long
28 | // as you specify a parent activity in AndroidManifest.xml.
29 | return when (item.itemId) {
30 | R.id.action_settings -> true
31 | else -> super.onOptionsItemSelected(item)
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
7 |
9 |
11 |
12 |
13 |
14 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
7 |
9 |
11 |
13 |
15 |
17 |
19 |
21 |
23 |
25 |
27 |
29 |
31 |
33 |
35 |
37 |
39 |
41 |
43 |
45 |
47 |
49 |
51 |
53 |
55 |
57 |
59 |
61 |
63 |
65 |
67 |
69 |
70 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
8 |
9 |
12 |
13 |
14 |
15 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w1240dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 200dp
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CommonUtils
3 | Settings
4 |
5 | First Fragment
6 | Second Fragment
7 | Next
8 | Previous
9 |
10 | Hello first fragment
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | }
6 | dependencies {
7 | // https://mvnrepository.com/artifact/com.android.tools.build/gradle?repo=google
8 | classpath 'com.android.tools.build:gradle:8.5.2'
9 | // https://kotlinlang.org/docs/reference/using-gradle.html https://plugins.gradle.org/plugin/org.jetbrains.kotlin.android
10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10"
11 | }
12 | }
13 |
14 | allprojects {
15 | repositories {
16 | google()
17 | mavenCentral()
18 | }
19 | }
20 |
21 | tasks.register('clean', Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. For more details, visit
12 | # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=obsolete
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 | org.gradle.configuration-cache=true
25 |
26 | #https://dev.to/cdsap/gradle-811-faster-configuration-cache-and-improved-configuration-time-ja1
27 | org.gradle.configuration-cache.parallel=true
28 | android.defaults.buildfeatures.buildconfig=false
29 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Dec 10 16:02:37 IST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | before_install:
2 | - sdk install java 17.0.1-open
3 | - sdk use java 17.0.1-open
4 |
5 | jdk:
6 | -openjdk17
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | id 'maven-publish'
5 | }
6 |
7 | android {
8 | compileSdk 35
9 |
10 | defaultConfig {
11 | minSdk 21
12 | targetSdk 35
13 | consumerProguardFiles "consumer-rules.pro"
14 | }
15 |
16 | buildTypes {
17 | release {
18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | compileOptions {
22 | sourceCompatibility JavaVersion.VERSION_17
23 | targetCompatibility JavaVersion.VERSION_17
24 | }
25 | kotlinOptions {
26 | jvmTarget = "17"
27 | }
28 | buildFeatures {
29 | viewBinding true
30 | buildConfig = false
31 | }
32 | namespace 'com.lb.common_utils'
33 |
34 |
35 | }
36 | afterEvaluate {
37 | publishing {
38 | publications {
39 | release(MavenPublication) {
40 | from components.release
41 | }
42 | }
43 | }
44 | }
45 | dependencies {
46 | api 'androidx.core:core-ktx:1.15.0'
47 | api 'com.google.android.material:material:1.12.0'
48 | api 'androidx.work:work-runtime-ktx:2.10.0'
49 | api 'androidx.preference:preference-ktx:1.2.1'
50 | }
51 |
--------------------------------------------------------------------------------
/library/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidDeveloperLB/CommonUtils/873138aa41cdac3fd8326b312efb597da888b31a/library/consumer-rules.pro
--------------------------------------------------------------------------------
/library/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | -openjdk11
3 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/AdmobTestAdUnitIds.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | //https://developers.google.com/admob/android/test-ads
4 | object AdmobTestAdUnitIds {
5 | /**https://developers.google.com/admob/android/app-open#always_test_with_test_ads*/
6 | const val APP_OPEN = "ca-app-pub-3940256099942544/9257395921"
7 |
8 | /**https://developers.google.com/admob/android/banner#always_test_with_test_ads*/
9 | const val BANNER_ADAPTIVE = "ca-app-pub-3940256099942544/9214589741"
10 |
11 | /**https://developers.google.com/admob/android/banner/fixed-size#add-adview*/
12 | const val BANNER = "ca-app-pub-3940256099942544/6300978111"
13 |
14 | /** https://developers.google.com/admob/android/banner/inline-adaptive https://github.com/googleads/googleads-mobile-ios-examples/blob/6def5ddd3f4b0b92b9fc8fec3e88e011c21f36b5/Swift/admob/AdaptiveBannerExample/AdaptiveBannerExample/ViewController.swift#LL28C28-L28C66 https://groups.google.com/g/google-admob-ads-sdk/c/sENzJ0kycfE */
15 | const val BANNER_INLINE_ADAPTIVE = "ca-app-pub-3940256099942544/2435281174"
16 |
17 | /**https://developers.google.com/admob/android/interstitial#always_test_with_test_ads*/
18 | const val INTERSTITIAL = "ca-app-pub-3940256099942544/1033173712"
19 |
20 | const val INTERSTITIAL_VIDEO = "ca-app-pub-3940256099942544/8691691433"
21 |
22 | /**https://developers.google.com/admob/android/rewarded-interstitial#load_an_ad_2*/
23 | const val INTERSTITIAL_REWARDED = "ca-app-pub-3940256099942544/5354046379"
24 |
25 | /**https://developers.google.com/admob/android/rewarded#always_test_with_test_ads*/
26 | const val REWARDED = "ca-app-pub-3940256099942544/5224354917"
27 |
28 | /**https://developers.google.com/admob/android/native#always_test_with_test_ads_2*/
29 | const val NATIVE_IMAGE = "ca-app-pub-3940256099942544/2247696110"
30 |
31 | /**https://developers.google.com/admob/android/native/video-ads*/
32 | const val NATIVE_IMAGE_AND_VIDEO = "ca-app-pub-3940256099942544/1044960115"
33 |
34 | /** https://developers.google.com/admob/android/native/full-screen https://groups.google.com/g/google-admob-ads-sdk/c/sREXDkNNYuU https://www.google.com/url?sa=j&url=https%3A%2F%2Fgithub.com%2Fgoogleads%2Fgoogleads-mobile-android-examples%2Fblob%2F7829ae98c4925d547c149c6aa71a25930adb79d2%2Fjava%2Fadmob%2FFullScreenNativeExample%2Fapp%2Fsrc%2Fmain%2Fjava%2Fcom%2Fgoogle%2Fexample%2Fgms%2Ffullscreennativeexample%2FNativeAdsPool.java%23L48&uct=1705091050&usg=lxSuTFHWRfv6H28_h5mIwMe5WT8.&opi=112976253*/
35 | const val NATIVE_FULL_SCREEN = "ca-app-pub-3940256099942544/7342230711"
36 | }
37 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/BaseViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.annotation.SuppressLint
4 | import android.app.Application
5 | import android.content.Context
6 | import android.os.Handler
7 | import android.os.Looper
8 | import androidx.lifecycle.AndroidViewModel
9 |
10 | /**usage: class MyViewModel(application: Application) : BaseViewModel(application)
11 | * getting instance: private lateinit var viewModel: MyViewModel
12 | * viewModel=ViewModelProvider(this).get(MyViewModel::class.java)*/
13 | abstract class BaseViewModel(application: Application) : AndroidViewModel(application) {
14 | @Suppress("MemberVisibilityCanBePrivate")
15 | var isCleared = false
16 | val onClearedListeners = ArrayList()
17 |
18 | @SuppressLint("StaticFieldLeak")
19 | @Suppress("LeakingThis")
20 | val applicationContext: Context = application.applicationContext
21 | val handler = Handler(Looper.getMainLooper())
22 |
23 | override fun onCleared() {
24 | super.onCleared()
25 | isCleared = true
26 | onClearedListeners.forEach { it.run() }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/BundleEx.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.content.Intent
4 | import android.os.Build
5 | import android.os.Build.VERSION_CODES
6 | import android.os.Bundle
7 | import android.os.Parcelable
8 | import java.io.Serializable
9 |
10 |
11 | fun Intent.getBooleanExtraOrNull(key: String): Boolean? =
12 | if (this.hasExtra(key)) getBooleanExtra(key, false) else null
13 |
14 | fun Bundle.getIntOrNull(key: String): Int? = if (this.containsKey(key)) getInt(key) else null
15 | fun Intent.getIntExtraOrNull(key: String): Int? =
16 | if (this.hasExtra(key)) getIntExtra(key, 0) else null
17 |
18 | fun Intent.getLongExtraOrNull(key: String): Long? =
19 | if (this.hasExtra(key)) getLongExtra(key, 0L) else null
20 |
21 | fun Bundle.getLongOrNull(key: String): Long? =
22 | if (this.containsKey(key)) this.getLong(key) else null
23 |
24 | inline fun Intent.getParcelableExtraCompat(key: String): T? = when {
25 | Build.VERSION.SDK_INT > VERSION_CODES.TIRAMISU -> getParcelableExtra(key, T::class.java)
26 | else -> @Suppress("DEPRECATION") getParcelableExtra(key) as? T?
27 | }
28 |
29 | inline fun Bundle.getParcelableCompat(key: String): T? = when {
30 | Build.VERSION.SDK_INT > VERSION_CODES.TIRAMISU -> getParcelable(key, T::class.java)
31 | else -> @Suppress("DEPRECATION") getParcelable(key) as? T?
32 | }
33 |
34 | inline fun Bundle.getParcelableArrayListCompat(key: String): ArrayList? =
35 | when {
36 | Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU -> getParcelableArrayList(key, T::class.java)
37 | else -> @Suppress("DEPRECATION") getParcelableArrayList(key)
38 | }
39 |
40 | inline fun Intent.getParcelableArrayListExtraCompat(key: String): ArrayList? =
41 | when {
42 | Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU -> getParcelableArrayListExtra(key, T::class.java)
43 | else -> @Suppress("DEPRECATION") getParcelableArrayListExtra(key)
44 | }
45 |
46 |
47 | inline fun Intent.getSerializableExtraCompat(key: String): T? = when {
48 | Build.VERSION.SDK_INT >= VERSION_CODES.TIRAMISU -> getSerializableExtra(key, T::class.java)
49 | else -> @Suppress("DEPRECATION") getSerializableExtra(key) as? T?
50 | }
51 |
52 | inline fun Bundle.getSerializableCompat(key: String): T? = when {
53 | Build.VERSION.SDK_INT >= VERSION_CODES.TIRAMISU -> getSerializable(key, T::class.java)
54 | else -> @Suppress("DEPRECATION") getSerializable(key) as? T?
55 | }
56 |
57 | inline fun > enumValueOfOrNull(name: String?): EnumType? =
58 | name?.runCatching { enumValueOf(this) }
59 | ?.getOrNull()
60 |
61 |
62 | inline fun > enumValueOrDefault(
63 | name: String?,
64 | defaultValue: () -> EnumType
65 | ): EnumType = enumValueOfOrNull(name)
66 | ?: defaultValue.invoke()
67 | //
68 | //object BundleEx {
69 | //}
70 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/CollectionUtil.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import java.text.CollationKey
4 | import java.text.Collator
5 |
6 | fun Array<*>?.sizeSafe() = this?.size ?: 0
7 | fun Collection<*>?.sizeSafe() = this?.size ?: 0
8 | fun Map<*, *>?.sizeSafe() = this?.size ?: 0
9 |
10 | fun MutableMap.putMultipleKeysToSameValue(value: S, vararg keys: T) {
11 | keys.forEach { key -> this[key] = value }
12 | }
13 |
14 | fun Array.toArrayList() = ArrayList(this.size).apply { addAll(this@toArrayList) }
15 |
16 | fun ArrayList.sortUsingCollator(collator: Collator = Collator.getInstance(), alternativeComparator: Comparator? = null) {
17 | if (size <= 1)
18 | return
19 | val hashMap = HashMap(size)
20 | sortWith { o1, o2 ->
21 | val key1 = hashMap.getOrPut(o1) {
22 | collator.getCollationKey(o1)
23 | }
24 | val key2 = hashMap.getOrPut(o2) {
25 | collator.getCollationKey(o2)
26 | }
27 | val result = key1.compareTo(key2)
28 | if (result != 0)
29 | return@sortWith result
30 | return@sortWith alternativeComparator?.compare(o1, o2) ?: result
31 | }
32 | }
33 |
34 | fun ArrayList.sortUsingCollator(collator: Collator = Collator.getInstance(), getStringValue: (input: T) -> String, alternativeComparator: Comparator? = null) {
35 | if (size <= 1)
36 | return
37 | val hashMap = HashMap(size)
38 | sortWith { o1, o2 ->
39 | val o1Str = getStringValue(o1)
40 | val o2Str = getStringValue(o2)
41 | val key1 = hashMap.getOrPut(o1Str) {
42 | collator.getCollationKey(o1Str)
43 | }
44 | val key2 = hashMap.getOrPut(o2Str) {
45 | collator.getCollationKey(o2Str)
46 | }
47 | val result = key1.compareTo(key2)
48 | if (result != 0)
49 | return@sortWith result
50 | return@sortWith alternativeComparator?.compare(o1, o2) ?: result
51 | }
52 | }
53 |
54 | object CollectionUtil {
55 | fun isEmpty(arr: Array?): Boolean {
56 | return arr == null || arr.isEmpty()
57 | }
58 |
59 | fun isEmpty(collection: Collection?): Boolean {
60 | return collection == null || collection.isEmpty()
61 | }
62 |
63 | fun size(collection: Collection?): Int {
64 | return collection?.size ?: 0
65 | }
66 |
67 | /**
68 | * returns true iff all of the items on each set exist on the other set .
69 | */
70 | fun areSetsIdentical(set1: Set?, set2: Set?): Boolean {
71 | // both are the same , so return true
72 | if (set1 === set2)
73 | return true
74 | // size is different so return false
75 | if (size(set1) != size(set2))
76 | return false
77 | // both are empty , so return true
78 | if (isEmpty(set1))
79 | return true
80 | // size is the same , so compare items
81 | for (t in set1!!)
82 | if (!set2!!.contains(t))
83 | return false
84 | return true
85 | }
86 |
87 | /**
88 | * adds all items from src to dst
89 | */
90 | fun addAll(src: Array?, dst: MutableCollection) {
91 | src?.let { java.util.Collections.addAll(dst, *it) }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/DialogFragmentCompatEx.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.os.Bundle
4 | import androidx.fragment.app.DialogFragment
5 | import androidx.fragment.app.Fragment
6 | import androidx.fragment.app.FragmentActivity
7 | import androidx.fragment.app.FragmentManager
8 |
9 | val DialogFragment.argumentsSafe: Bundle
10 | get() = arguments ?: Bundle().also { arguments = it }
11 |
12 | fun DialogFragment.showAllowStateLoss(fragmentManager: FragmentManager, tag: String? = null) = fragmentManager.beginTransaction().add(this, tag).commitAllowingStateLoss() >= 0
13 |
14 | fun DialogFragment.showAllowStateLoss(activity: FragmentActivity, tag: String? = null) = activity.supportFragmentManager.beginTransaction().add(this, tag).commitAllowingStateLoss() >= 0
15 |
16 | fun DialogFragment.showAllowStateLoss(fragment: Fragment, tag: String? = null) = fragment.childFragmentManager.beginTransaction().add(this, tag).commitAllowingStateLoss() >= 0
17 |
18 | fun DialogFragment.show(activity: FragmentActivity, tag: String) {
19 | show(activity.supportFragmentManager, tag)
20 | }
21 |
22 | fun DialogFragment.show(fragment: Fragment, tag: String) {
23 | show(fragment.childFragmentManager, tag)
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/EmptyActivityLifecycleCallbacksEx.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.os.Bundle
6 |
7 | /**Same as the internal class of androidx.lifecycle.EmptyActivityLifecycleCallbacks, but public https://issuetracker.google.com/issues/207842543*/
8 | open class EmptyActivityLifecycleCallbacksEx : Application.ActivityLifecycleCallbacks {
9 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
10 | override fun onActivityStarted(activity: Activity) {}
11 | override fun onActivityResumed(activity: Activity) {}
12 | override fun onActivityPaused(activity: Activity) {}
13 | override fun onActivityStopped(activity: Activity) {}
14 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
15 | override fun onActivityDestroyed(activity: Activity) {}
16 | }
17 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/FragmentViewBindingDelegate.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.appcompat.app.AppCompatActivity
8 | import androidx.fragment.app.DialogFragment
9 | import androidx.fragment.app.Fragment
10 | import androidx.lifecycle.DefaultLifecycleObserver
11 | import androidx.lifecycle.Lifecycle
12 | import androidx.lifecycle.LifecycleOwner
13 | import androidx.lifecycle.Observer
14 | import androidx.recyclerview.widget.RecyclerView
15 | import androidx.viewbinding.ViewBinding
16 | import kotlin.properties.ReadOnlyProperty
17 | import kotlin.reflect.KProperty
18 |
19 | //usage examples: https://gist.github.com/gmk57/aefa53e9736d4d4fb2284596fb62710d
20 |
21 | fun AppCompatActivity.setContentView(binding: ViewBinding) = setContentView(binding.root)
22 |
23 | @Suppress("MemberVisibilityCanBePrivate")
24 | open class BoundViewHolder(
25 | val binding: ViewBindingType,
26 | holderView: View = binding.root
27 | ) : RecyclerView.ViewHolder(holderView)
28 |
29 | /**usage: private val binding by viewBinding(MainActivityBinding::inflate)*/
30 | inline fun AppCompatActivity.viewBinding(crossinline bindingInflater: (LayoutInflater) -> T) =
31 | lazy(LazyThreadSafetyMode.NONE) {
32 | bindingInflater.invoke(layoutInflater)
33 | }
34 |
35 |
36 | /**usage: Fragment(R.layout.first_fragment)
37 | * private val binding by viewBinding(FirstFragmentBinding::bind)*/
38 | fun Fragment.viewBinding(viewBindingFactory: (View) -> T) =
39 | FragmentViewBindingDelegate(this, viewBindingFactory)
40 |
41 | /** usage: class MyFragment:DialogFragment()
42 | * private val binding by viewBinding(MyFragmentBinding::inflate)
43 | * override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
44 | * return AlertDialog.Builder(requireContext()).setView(binding.root).create()
45 | * }
46 | * or:
47 | * class MyFragment:DialogFragment(R.layout.fragment) {
48 | * private val binding by viewBinding(FragmentBinding::bind)
49 | */
50 | inline fun DialogFragment.viewBinding(crossinline factory: (LayoutInflater) -> T) =
51 | lazy(LazyThreadSafetyMode.NONE) {
52 | factory(layoutInflater)
53 | }
54 |
55 | abstract class BoundActivity(private val factory: (LayoutInflater) -> T) :
56 | AppCompatActivity() {
57 | @Suppress("MemberVisibilityCanBePrivate")
58 | lateinit var binding: T
59 |
60 | override fun onCreate(savedInstanceState: Bundle?) {
61 | super.onCreate(savedInstanceState)
62 | binding = factory(layoutInflater)
63 | setContentView(binding.root)
64 | }
65 | }
66 |
67 | abstract class BoundFragment(private val factory: (LayoutInflater, ViewGroup?, Boolean) -> T) :
68 | Fragment() {
69 | @Suppress("MemberVisibilityCanBePrivate")
70 | protected var binding: T? = null
71 |
72 | override fun onCreateView(
73 | inflater: LayoutInflater,
74 | container: ViewGroup?,
75 | savedInstanceState: Bundle?
76 | ): View? {
77 | binding = factory(inflater, container, false)
78 | return binding?.root
79 | }
80 |
81 | override fun onDestroyView() {
82 | super.onDestroyView()
83 | binding = null
84 | }
85 | }
86 |
87 | class FragmentViewBindingDelegate(
88 | val fragment: Fragment,
89 | val viewBindingFactory: (View) -> T
90 | ) : ReadOnlyProperty {
91 | private var binding: T? = null
92 |
93 | init {
94 | fragment.lifecycle.addObserver(object : DefaultLifecycleObserver {
95 | val viewLifecycleOwnerLiveDataObserver =
96 | Observer {
97 | val viewLifecycleOwner = it ?: return@Observer
98 | viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
99 | override fun onDestroy(owner: LifecycleOwner) {
100 | binding = null
101 | }
102 | })
103 | }
104 |
105 | override fun onCreate(owner: LifecycleOwner) {
106 | fragment.viewLifecycleOwnerLiveData.observeForever(
107 | viewLifecycleOwnerLiveDataObserver
108 | )
109 | }
110 |
111 | override fun onDestroy(owner: LifecycleOwner) {
112 | fragment.viewLifecycleOwnerLiveData.removeObserver(
113 | viewLifecycleOwnerLiveDataObserver
114 | )
115 | }
116 | })
117 | }
118 |
119 | override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
120 | binding?.let { return it }
121 | val lifecycle = fragment.viewLifecycleOwner.lifecycle
122 | if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED))
123 | throw IllegalStateException("Should not attempt to get bindings when Fragment views are destroyed.")
124 | return viewBindingFactory(thisRef.requireView()).also { this.binding = it }
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/PreferenceUtil.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.content.Context
4 | import android.content.SharedPreferences
5 | import androidx.annotation.AnyThread
6 | import androidx.annotation.ArrayRes
7 | import androidx.annotation.BoolRes
8 | import androidx.annotation.IntegerRes
9 | import androidx.annotation.StringRes
10 | import androidx.preference.ListPreference
11 | import androidx.preference.Preference
12 | import androidx.preference.PreferenceFragmentCompat
13 | import androidx.preference.PreferenceGroup
14 | import androidx.preference.PreferenceManager
15 | import androidx.preference.PreferenceScreen
16 | import org.json.JSONArray
17 | import org.json.JSONException
18 | import java.util.EnumSet
19 | import java.util.Stack
20 |
21 | fun PreferenceFragmentCompat.findPreference(@StringRes prefKey: Int): Preference =
22 | findPreference(getString(prefKey))!!
23 |
24 | @Suppress("unused")
25 | object PreferenceUtil {
26 | @Volatile
27 | private var sharedPreferences: SharedPreferences? = null
28 |
29 | fun getDefaultSharedPreferences(context: Context): SharedPreferences {
30 | this.sharedPreferences?.let { return it }
31 | synchronized(this) {
32 | this.sharedPreferences?.let { return it }
33 | val result = PreferenceManager.getDefaultSharedPreferences(context)!!
34 | this.sharedPreferences = result
35 | return result
36 | }
37 | }
38 |
39 | fun prepareListPreference(
40 | fragment: PreferenceFragmentCompat,
41 | prefKeyId: Int, //
42 | @ArrayRes entriesId: Int,
43 | @ArrayRes valuesId: Int,
44 | @StringRes defaultValueId: Int,
45 | listener: OnListPreferenceChosenListener?
46 | ): ListPreference {
47 | val entries = fragment.resources.getStringArray(entriesId)
48 | val values = fragment.resources.getStringArray(valuesId)
49 | return prepareListPreference(fragment, prefKeyId, entries, values, defaultValueId, listener)
50 | }
51 |
52 | fun prepareListPreference(
53 | fragment: PreferenceFragmentCompat,
54 | @StringRes prefKeyId: Int,
55 | entries: Array,
56 | values: Array,
57 | @StringRes defaultValueId: Int,
58 | listener: OnListPreferenceChosenListener?
59 | ): ListPreference {
60 | val defaultValue = fragment.resources.getString(defaultValueId)
61 | return prepareListPreference(fragment, prefKeyId, entries, values, defaultValue, listener)
62 | }
63 |
64 | fun prepareListPreference(
65 | fragment: PreferenceFragmentCompat,
66 | @StringRes prefKeyId: Int,
67 | entries: Array,
68 | values: Array,
69 | defaultValue: String?,
70 | listener: OnListPreferenceChosenListener?
71 | ): ListPreference {
72 | val prefKey = fragment.getString(prefKeyId)
73 | val pref = fragment.findPreference(prefKey)
74 | val currentValue = getDefaultSharedPreferences(fragment.activity!!)
75 | .getString(prefKey, null)
76 | pref!!.setDefaultValue(defaultValue)
77 | pref.summary = "%s"
78 | if (currentValue == null)
79 | pref.value = defaultValue
80 | pref.entryValues = values
81 | pref.entries = entries
82 | pref.setOnPreferenceChangeListener { _, newValue ->
83 | val newValueStr = newValue.toString()
84 | return@setOnPreferenceChangeListener listener?.onChosenPreference(prefKey, newValueStr)
85 | ?: true
86 | }
87 | return pref
88 | }
89 |
90 | // enum
91 | inline fun > getEnumPref(
92 | context: Context,
93 | @StringRes prefKeyResId: Int,
94 | @StringRes prefDefaultValueResId: Int
95 | ): EnumType {
96 | val value = getStringPref(context, prefKeyResId, prefDefaultValueResId)
97 | return value?.runCatching { enumValueOf(this) }
98 | ?.getOrNull() ?: enumValueOf(context.getString(prefDefaultValueResId))
99 | }
100 |
101 | inline fun > getEnumPref(
102 | context: Context,
103 | @StringRes prefKeyResId: Int,
104 | prefDefaultValue: EnumType
105 | ): EnumType {
106 | val value = getStringPref(context, prefKeyResId, prefDefaultValue.name)
107 | return value?.runCatching { enumValueOf(this) }
108 | ?.getOrNull() ?: prefDefaultValue
109 | }
110 |
111 | fun > putEnumPref(
112 | context: Context,
113 | @StringRes prefKeyResId: Int,
114 | enumValue: EnumType?
115 | ) {
116 | putStringPref(context, prefKeyResId, enumValue?.name)
117 | }
118 |
119 | // enumset
120 | fun > getEnumSetPref(
121 | context: Context,
122 | @StringRes prefKeyResId: Int,
123 | @StringRes prefDefaultValueResId: Int,
124 | enumClass: Class
125 | ): EnumSet {
126 | val value = getStringPref(context, prefKeyResId, prefDefaultValueResId)
127 | val result = EnumSet.noneOf(enumClass)
128 | if (value.isNullOrEmpty())
129 | return EnumSet.noneOf(enumClass)
130 | val split = value.split(',').dropLastWhile { it.isEmpty() }.toTypedArray()
131 | for (str in split)
132 | if (str.trim { it <= ' ' }.isNotEmpty())
133 | result.add(java.lang.Enum.valueOf(enumClass, str))
134 | return result
135 | }
136 |
137 | fun > putEnumCollectionPref(
138 | context: Context,
139 | @StringRes prefKeyResId: Int,
140 | enumCollection: Collection?
141 | ) {
142 | val valToPut: String? = when {
143 | enumCollection.isNullOrEmpty() -> null
144 | enumCollection.size == 1 -> enumCollection.iterator().next().name
145 | else -> {
146 | val sb = StringBuilder()
147 | for (enumVal in enumCollection)
148 | sb.append(enumVal.name).append(',')
149 | sb.toString()
150 | }
151 | }
152 | putStringPref(context, prefKeyResId, valToPut)
153 | }
154 |
155 | //enum list
156 | fun > getEnumListPref(
157 | context: Context, @StringRes prefKeyResId: Int, @StringRes prefDefaultValueResId: Int,
158 | enumClass: Class
159 | ): List {
160 | val value = getStringPref(context, prefKeyResId, prefDefaultValueResId)
161 | val result = ArrayList()
162 | if (value.isNullOrEmpty())
163 | return result
164 | val split = value.split(',').dropLastWhile { it.isEmpty() }.toTypedArray()
165 | for (str in split)
166 | if (str.trim { it <= ' ' }.isNotEmpty())
167 | result.add(java.lang.Enum.valueOf(enumClass, str))
168 | return result
169 | }
170 |
171 | //enum list
172 | fun > getEnumListPref(
173 | context: Context,
174 | @StringRes prefKeyResId: Int,
175 | enumClass: Class
176 | ): List? {
177 | if (!hasPreference(context, prefKeyResId))
178 | return null
179 | val value = getStringPref(context, prefKeyResId, 0)
180 | val result = ArrayList()
181 | if (value.isNullOrEmpty())
182 | return result
183 | val split = value.split(',').dropLastWhile { it.isEmpty() }.toTypedArray()
184 | for (str in split)
185 | if (str.trim { it <= ' ' }.isNotEmpty())
186 | result.add(java.lang.Enum.valueOf(enumClass, str))
187 | return result
188 | }
189 |
190 | // string
191 | fun getStringPref(context: Context, prefKey: String, defaultValue: String?): String? =
192 | getDefaultSharedPreferences(context).getString(prefKey, defaultValue)
193 |
194 | fun getStringPref(
195 | context: Context,
196 | @StringRes prefKeyResId: Int,
197 | @StringRes prefDefaultValueResId: Int
198 | ): String? {
199 | val prefKey = context.getString(prefKeyResId)
200 | val defaultValue = if (prefDefaultValueResId == 0) null else context.resources.getString(
201 | prefDefaultValueResId
202 | )
203 | return getDefaultSharedPreferences(context).getString(prefKey, defaultValue)
204 | }
205 |
206 | fun getStringPref(
207 | context: Context,
208 | @StringRes prefKeyResId: Int,
209 | defaultValue: String?
210 | ): String? {
211 | val prefKey = context.getString(prefKeyResId)
212 | return getDefaultSharedPreferences(context)
213 | .getString(prefKey, defaultValue)
214 | }
215 |
216 | fun putStringPref(context: Context, @StringRes prefKeyResId: Int, newValue: String?) {
217 | val prefKey = context.getString(prefKeyResId)
218 | val preferences = getDefaultSharedPreferences(context)
219 | preferences.edit().putString(prefKey, newValue).apply()
220 | }
221 |
222 | // boolean
223 | fun getBooleanPref(
224 | context: Context,
225 | @StringRes prefKeyResId: Int,
226 | @BoolRes prefDefaultValueResId: Int
227 | ): Boolean {
228 | return getDefaultSharedPreferences(context).getBoolean(
229 | context.getString(prefKeyResId),
230 | context.resources.getBoolean(prefDefaultValueResId)
231 | )
232 | }
233 |
234 | fun getBooleanPref(
235 | context: Context,
236 | prefKey: String,
237 | @BoolRes prefDefaultValueResId: Int
238 | ): Boolean {
239 | return getDefaultSharedPreferences(context)
240 | .getBoolean(prefKey, context.resources.getBoolean(prefDefaultValueResId))
241 | }
242 |
243 | fun getBooleanPref(context: Context, prefKey: String, defaultValue: Boolean): Boolean {
244 | return getDefaultSharedPreferences(context).getBoolean(prefKey, defaultValue)
245 | }
246 |
247 | // boolean
248 | fun getBooleanPref(
249 | context: Context,
250 | @StringRes prefKeyResId: Int,
251 | defaultValue: Boolean
252 | ): Boolean {
253 | return getDefaultSharedPreferences(context).getBoolean(context.getString(prefKeyResId), defaultValue)
254 | }
255 |
256 | fun putBooleanPref(context: Context, @StringRes prefKeyResId: Int, newValue: Boolean) {
257 | val prefKey = context.getString(prefKeyResId)
258 | val preferences = getDefaultSharedPreferences(context)
259 | preferences.edit().putBoolean(prefKey, newValue).apply()
260 | }
261 |
262 | // int
263 | fun getIntPrefOrDefaultIntFromResId(
264 | context: Context,
265 | @StringRes prefKeyResId: Int,
266 | @IntegerRes prefDefaultValueResId: Int
267 | ): Int {
268 | val prefKey = context.getString(prefKeyResId)
269 | val defaultValue = if (prefDefaultValueResId == 0) -1 else context.resources.getInteger(
270 | prefDefaultValueResId
271 | )
272 | return getDefaultSharedPreferences(context).getInt(prefKey, defaultValue)
273 | }
274 |
275 | fun getIntPref(context: Context, @StringRes prefKeyResId: Int, defaultValue: Int): Int {
276 | val prefKey = context.getString(prefKeyResId)
277 | return getDefaultSharedPreferences(context).getInt(prefKey, defaultValue)
278 | }
279 |
280 | /**
281 | * returns the int pref, or -1 if not available
282 | */
283 | fun getIntPref(context: Context, @StringRes prefKeyResId: Int): Int? {
284 | val prefKey = context.getString(prefKeyResId)
285 | val preferences = getDefaultSharedPreferences(context)
286 | return if (!preferences.contains(prefKey)) null else preferences.getInt(prefKey, -1)
287 | }
288 |
289 | fun putIntPref(context: Context, @StringRes prefKeyResId: Int, newValue: Int) {
290 | val prefKey = context.getString(prefKeyResId)
291 | val preferences = getDefaultSharedPreferences(context)
292 | preferences.edit().putInt(prefKey, newValue).apply()
293 | }
294 |
295 | fun putLongPref(context: Context, @StringRes prefKeyResId: Int, newValue: Long) {
296 | val prefKey = context.getString(prefKeyResId)
297 | val preferences = getDefaultSharedPreferences(context)
298 | preferences.edit().putLong(prefKey, newValue).apply()
299 | }
300 |
301 | fun getLongPref(context: Context, @StringRes prefKeyResId: Int): Long? {
302 | val prefKey = context.getString(prefKeyResId)
303 | val preferences = getDefaultSharedPreferences(context)
304 | return if (!preferences.contains(prefKey)) null else preferences.getLong(prefKey, -1)
305 | }
306 |
307 | // dimen
308 | fun getDimenAsStringPref(
309 | context: Context,
310 | @StringRes prefKeyResId: Int,
311 | prefDefaultValueResId: Int
312 | ): Float {
313 | val prefKey = context.getString(prefKeyResId)
314 | val res = context.resources
315 | val preferences = getDefaultSharedPreferences(context)
316 | val string = preferences.getString(prefKey, null)
317 | ?: return res.getDimension(prefDefaultValueResId) / res.displayMetrics.density
318 | return java.lang.Float.parseFloat(string)
319 | }
320 |
321 | fun putDimenAsStringPref(context: Context, @StringRes prefKeyResId: Int, newValue: Float) {
322 | putStringPref(context, prefKeyResId, newValue.toString())
323 | }
324 |
325 | // string set
326 | fun putStringCollection(
327 | context: Context,
328 | @StringRes prefKeyResId: Int,
329 | newValue: Collection?
330 | ) {
331 | val editor = getDefaultSharedPreferences(context).edit()
332 | val key = context.getString(prefKeyResId)
333 | if (newValue == null)
334 | editor.remove(key).apply()
335 | else
336 | editor.putString(key, JSONArray(newValue).toString()).apply()
337 | }
338 |
339 | fun getStringSet(context: Context, @StringRes prefKeyResId: Int): Set? {
340 | val key = context.getString(prefKeyResId)
341 | val str = getDefaultSharedPreferences(context).getString(key, null)
342 | ?: return null
343 | try {
344 | val jsonArray = JSONArray(str)
345 | val result = HashSet()
346 | for (i in 0 until jsonArray.length())
347 | result.add(jsonArray.getString(i))
348 | return result
349 | } catch (e: JSONException) {
350 | e.printStackTrace()
351 | getDefaultSharedPreferences(context).edit().remove(key).apply()
352 | }
353 |
354 | return null
355 | }
356 |
357 | // preference existence
358 | fun hasPreference(context: Context, @StringRes prefKeyResId: Int): Boolean {
359 | val prefKey = context.getString(prefKeyResId)
360 | val preferences = getDefaultSharedPreferences(context)
361 | return preferences.contains(prefKey)
362 | }
363 |
364 | // preference deletion
365 |
366 | fun removePreference(context: Context, @StringRes prefKeyResId: Int) {
367 | val prefKey = context.getString(prefKeyResId)
368 | val preferences = getDefaultSharedPreferences(context)
369 | preferences.edit().remove(prefKey).apply()
370 | }
371 |
372 | fun removePreference(context: Context, @StringRes vararg prefKeyResIds: Int) {
373 | val editor = getDefaultSharedPreferences(context).edit()
374 | prefKeyResIds.forEach { prefKeyResId ->
375 | val prefKey = context.getString(prefKeyResId)
376 | editor.remove(prefKey)
377 | }
378 | editor.apply()
379 | }
380 |
381 | fun removePreference(context: Context, prefKey: String) {
382 | getDefaultSharedPreferences(context).edit().remove(prefKey).apply()
383 | }
384 |
385 | @AnyThread
386 | fun removePreferences(context: Context, vararg prefKeys: String) {
387 | val editor = getDefaultSharedPreferences(context).edit()
388 | prefKeys.forEach {
389 | editor.remove(it)
390 | }
391 | editor.apply()
392 | }
393 |
394 | fun buildPreferenceParentTree(preferenceScreen: PreferenceScreen): Map {
395 | val result = HashMap()
396 | val curParents = Stack()
397 | curParents.add(preferenceScreen)
398 | while (!curParents.isEmpty()) {
399 | val parent = curParents.pop()
400 | val childCount = parent.preferenceCount
401 | for (i in 0 until childCount) {
402 | val child = parent.getPreference(i)
403 | result[child] = parent
404 | if (child is PreferenceGroup)
405 | curParents.push(child)
406 | }
407 | }
408 | return result
409 | }
410 |
411 | fun interface OnListPreferenceChosenListener {
412 | fun onChosenPreference(key: String, value: String): Boolean
413 | }
414 | }
415 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/SpanFormatter.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.text.SpannableStringBuilder
4 | import android.text.Spanned
5 | import android.text.SpannedString
6 | import com.lb.common_utils.SpanFormatter.format
7 | import java.util.Locale
8 | import java.util.regex.Pattern
9 |
10 | /*
11 | * Copyright © 2014 George T. Steel
12 | *
13 | * Licensed under the Apache License, Version 2.0 (the "License");
14 | * you may not use this file except in compliance with the License.
15 | * You may obtain a copy of the License at
16 | *
17 | * http://www.apache.org/licenses/LICENSE-2.0
18 | *
19 | * Unless required by applicable law or agreed to in writing, software
20 | * distributed under the License is distributed on an "AS IS" BASIS,
21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 | * See the License for the specific language governing permissions and
23 | * limitations under the License.
24 | */
25 | //https://github.com/george-steel/android-utils/blob/master/src/org/oshkimaadziig/george/androidutils/SpanFormatter.java
26 | /**
27 | * Provides [String.format] style functions that work with [Spanned] strings and preserve formatting.
28 | *
29 | * @author George T. Steel
30 | */
31 | object SpanFormatter {
32 | private val FORMAT_SEQUENCE: Pattern = Pattern.compile("%([0-9]+\\$|)([^a-zA-z%]*)([a-zA-Z%&&[^tT]]|[tT][a-zA-Z])")
33 |
34 | /**
35 | * Version of [String.format] that works on [Spanned] strings to preserve rich text formatting.
36 | * Both the `format` as well as any `%s args` can be Spanned and will have their formatting preserved.
37 | * Due to the way [android.text.Spannable]s work, any argument's spans will can only be included **once** in the result.
38 | * Any duplicates will appear as text only.
39 | *
40 | * @param format the format string (see [java.util.Formatter.format])
41 | * @param args
42 | * the list of arguments passed to the formatter. If there are
43 | * more arguments than required by `format`,
44 | * additional arguments are ignored.
45 | * @return the formatted string (with spans).
46 | */
47 | fun format(format: CharSequence?, vararg args: Any?): SpannedString {
48 | return format(Locale.getDefault(), format, *args)
49 | }
50 |
51 | /**
52 | * Version of [String.format] that works on [Spanned] strings to preserve rich text formatting.
53 | * Both the `format` as well as any `%s args` can be Spanned and will have their formatting preserved.
54 | * Due to the way [android.text.Spannable]s work, any argument's spans will can only be included **once** in the result.
55 | * Any duplicates will appear as text only.
56 | *
57 | * @param locale
58 | * the locale to apply; `null` value means no localization.
59 | * @param format the format string (see [java.util.Formatter.format])
60 | * @param args
61 | * the list of arguments passed to the formatter.
62 | * @return the formatted string (with spans).
63 | * @see String.format
64 | */
65 | fun format(locale: Locale, format: CharSequence?, vararg args: Any?): SpannedString {
66 | val out = SpannableStringBuilder(format)
67 | var i = 0
68 | var argAt: Int = -1
69 | while (i < out.length) {
70 | val m: java.util.regex.Matcher = FORMAT_SEQUENCE.matcher(out)
71 | if (!m.find(i))
72 | break
73 | i = m.start()
74 | val exprEnd: Int = m.end()
75 | val argTerm: String? = m.group(1)
76 | val modTerm: String? = m.group(2)
77 | val typeTerm: String? = m.group(3)
78 | var cookedArg: CharSequence
79 | when (typeTerm) {
80 | "%" -> cookedArg = "%"
81 | "n" -> cookedArg = "\n"
82 | else -> {
83 | val argIdx: Int = when (argTerm) {
84 | "" -> ++argAt
85 | "<" -> argAt
86 | else -> argTerm!!.substring(0, argTerm.length - 1).toInt() - 1
87 | }
88 | val argItem: Any? = args[argIdx]
89 | cookedArg = if ((typeTerm == "s") && argItem is Spanned) {
90 | argItem
91 | } else {
92 | String.format(locale, "%$modTerm$typeTerm", argItem)
93 | }
94 | }
95 | }
96 | out.replace(i, exprEnd, cookedArg)
97 | i += cookedArg.length
98 | }
99 | return SpannedString(out)
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/StatefulData.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | sealed class StatefulData {
4 | class Success(val data: T) : StatefulData()
5 | class Error(val throwable: Throwable? = null) : StatefulData()
6 | class Loading(val loadingData: Any? = null) : StatefulData()
7 | }
8 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/StringsUtil.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import androidx.annotation.IntRange
4 | import org.json.JSONArray
5 | import org.json.JSONException
6 | import org.json.JSONObject
7 | import java.text.Normalizer
8 | import java.text.NumberFormat
9 | import java.util.Locale
10 |
11 | /**2.0f->"2"
12 | * 2f->"2"
13 | * -2.0f->"-2"
14 | * */
15 | fun Float.toStringWithoutDecimalPointIfPossible( ): String {
16 | val i = toInt()
17 | if (this == i.toFloat())
18 | return "$i"
19 | return "$this"
20 | }
21 |
22 | fun String?.toJSONObject(): JSONObject? {
23 | if (this == null)
24 | return null
25 | try {
26 | return JSONObject(this)
27 | } catch (_: JSONException) {
28 | }
29 | return null
30 | }
31 |
32 | fun String?.toJSONArray(): JSONArray? {
33 | if (this == null)
34 | return null
35 | try {
36 | return JSONArray(this)
37 | } catch (_: JSONException) {
38 | }
39 | return null
40 | }
41 |
42 | object StringsUtil {
43 | private val defaultNormalizationRegex: Regex by lazy {
44 | "[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+".toRegex()
45 | }
46 |
47 | interface BytesFormatter {
48 | /**called when the type of the result to format is Long. Example: 123KB
49 | * @param unitPowerIndex the unit-power we need to format to. Examples: 0 is bytes, 1 is kb, 2 is mb, etc...
50 | * available units and their order: B,K,M,G,T,P,E
51 | * @param isMetric true if each kilo==1000, false if kilo==1024
52 | * */
53 | fun onFormatLong(valueToFormat: Long, unitPowerIndex: Int, isMetric: Boolean): String
54 |
55 | /**called when the type of the result to format is Double. Example: 1.23KB
56 | * @param unitPowerIndex the unit-power we need to format to. Examples: 0 is bytes, 1 is kb, 2 is mb, etc...
57 | * available units and their order: B,K,M,G,T,P,E
58 | * @param isMetric true if each kilo==1000, false if kilo==1024
59 | * */
60 | fun onFormatDouble(valueToFormat: Double, unitPowerIndex: Int, isMetric: Boolean): String
61 | }
62 |
63 | /**removes Diacritic signs from text to be able to search them easier. Works only on some languages. Example : "ā" becomes "a"
64 | * Warning: has a rare crash on some devices (PatternSyntaxException) https://issuetracker.google.com/issues/310376033#comment3*/
65 | fun normalizeIfNeeded(
66 | string: CharSequence,
67 | form: Normalizer.Form = Normalizer.Form.NFD,
68 | regex: Regex = defaultNormalizationRegex
69 | ): CharSequence {
70 | if (Normalizer.isNormalized(string, form))
71 | return string
72 | val normalized = Normalizer.normalize(string, form)
73 | return normalized.replace(regex, "")
74 | }
75 |
76 | private val defaultBytesFormatter = object : BytesFormatter {
77 | val numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH).also {
78 | it.maximumFractionDigits = 2
79 | it.minimumFractionDigits = 0
80 | }
81 |
82 | private fun formatByUnit(
83 | formattedNumber: String,
84 | threePowerIndex: Int,
85 | isMetric: Boolean
86 | ): String {
87 | val sb = StringBuilder(formattedNumber.length + 4)
88 | sb.append(formattedNumber)
89 | val unitsToUse = "B${if (isMetric) "k" else "K"}MGTPE"
90 | sb.append(unitsToUse[threePowerIndex])
91 | if (threePowerIndex > 0)
92 | if (isMetric) sb.append('B') else sb.append("iB")
93 | return sb.toString()
94 | }
95 |
96 | override fun onFormatLong(
97 | valueToFormat: Long,
98 | unitPowerIndex: Int,
99 | isMetric: Boolean
100 | ): String {
101 | val formattedNumber = String.format(Locale.ENGLISH, "%,d", valueToFormat)
102 | return formatByUnit(formattedNumber, unitPowerIndex, isMetric)
103 | }
104 |
105 | override fun onFormatDouble(
106 | valueToFormat: Double,
107 | unitPowerIndex: Int,
108 | isMetric: Boolean
109 | ): String {
110 | //alternative for using numberFormat :
111 | //val formattedNumber = String.format("%,.2f", valueToFormat).let { initialFormattedString ->
112 | // if (initialFormattedString.contains('.'))
113 | // return@let initialFormattedString.dropLastWhile { it == '0' }
114 | // else return@let initialFormattedString
115 | //}
116 | return formatByUnit(numberFormat.format(valueToFormat), unitPowerIndex, isMetric)
117 | }
118 | }
119 |
120 | /**
121 | * formats the bytes to a human readable format, by providing the values to format later in the unit that we've found best to fit it
122 | *
123 | * @param isMetric true if each kilo==1000, false if kilo==1024
124 | * */
125 | fun bytesIntoHumanReadable(
126 | @IntRange(from = 0L) bytesToFormat: Long,
127 | bytesFormatter: BytesFormatter = defaultBytesFormatter,
128 | isMetric: Boolean = true
129 | ): String {
130 | val units = if (isMetric) 1000L else 1024L
131 | if (bytesToFormat < units)
132 | return bytesFormatter.onFormatLong(bytesToFormat, 0, isMetric)
133 | var bytesLeft = bytesToFormat
134 | var unitPowerIndex = 0
135 | while (unitPowerIndex < 6) {
136 | val newBytesLeft = bytesLeft / units
137 | if (newBytesLeft < units) {
138 | val byteLeftAsDouble = bytesLeft.toDouble() / units
139 | val needToShowAsInteger =
140 | byteLeftAsDouble == (bytesLeft / units).toDouble()
141 | ++unitPowerIndex
142 | if (needToShowAsInteger) {
143 | bytesLeft = newBytesLeft
144 | break
145 | }
146 | return bytesFormatter.onFormatDouble(byteLeftAsDouble, unitPowerIndex, isMetric)
147 | }
148 | bytesLeft = newBytesLeft
149 | ++unitPowerIndex
150 | }
151 | return bytesFormatter.onFormatLong(bytesLeft, unitPowerIndex, isMetric)
152 | }
153 |
154 | }
155 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/SystemProperties.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.annotation.SuppressLint
4 | import java.io.BufferedReader
5 | import java.io.IOException
6 | import java.io.InputStreamReader
7 | import java.lang.reflect.Method
8 |
9 | object SystemProperties {
10 | private var failedUsingReflection = false
11 | private var getPropMethod: Method? = null
12 |
13 | @SuppressLint("PrivateApi")
14 | fun getProp(propName: String, defaultResult: String = ""): String {
15 | if (!failedUsingReflection) try {
16 | if (getPropMethod == null) {
17 | val clazz = Class.forName("android.os.SystemProperties")
18 | getPropMethod = clazz.getMethod("get", String::class.java, String::class.java)
19 | }
20 | return getPropMethod!!.invoke(null, propName, defaultResult) as String? ?: defaultResult
21 | } catch (e: Exception) {
22 | getPropMethod = null
23 | failedUsingReflection = true
24 | }
25 | var process: Process? = null
26 | try {
27 | process = Runtime.getRuntime().exec("getprop $propName $defaultResult")
28 | val reader = BufferedReader(InputStreamReader(process.inputStream))
29 | return reader.readLine()
30 | } catch (e: IOException) {
31 | } finally {
32 | process?.destroy()
33 | }
34 | return defaultResult
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/SystemUtils.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.annotation.SuppressLint
4 | import android.app.Activity
5 | import android.app.ActivityManager
6 | import android.app.Application
7 | import android.app.ApplicationExitInfo
8 | import android.content.ComponentName
9 | import android.content.Context
10 | import android.content.Intent
11 | import android.content.pm.ActivityInfo
12 | import android.content.pm.PackageManager
13 | import android.content.pm.PackageManager.NameNotFoundException
14 | import android.content.pm.ResolveInfo
15 | import android.content.res.Resources
16 | import android.net.ConnectivityManager
17 | import android.os.Build
18 | import android.os.PowerManager
19 | import android.provider.Settings
20 | import android.system.OsConstants
21 | import android.view.WindowManager
22 | import androidx.annotation.RequiresApi
23 | import androidx.annotation.RequiresPermission
24 | import androidx.core.content.ContextCompat
25 | import java.io.File
26 | import java.security.MessageDigest
27 | import java.security.NoSuchAlgorithmException
28 | import java.util.Locale
29 | import java.util.regex.Pattern
30 | import kotlin.math.max
31 |
32 | @RequiresApi(Build.VERSION_CODES.R)
33 | fun ApplicationExitInfo.wasKilledByLowMemory(): Boolean {
34 | return if (ActivityManager.isLowMemoryKillReportSupported()) reason == ApplicationExitInfo.REASON_LOW_MEMORY
35 | else reason == ApplicationExitInfo.REASON_SIGNALED && status == OsConstants.SIGKILL
36 | }
37 |
38 | /**uses application context to make sure it will avoid memory leaks*/
39 | inline fun Context.getSystemServiceCompat(): T =
40 | ContextCompat.getSystemService(applicationContext, T::class.java)!!
41 |
42 | fun PackageManager.queryIntentActivitiesCompat(
43 | intent: Intent,
44 | flags: Long = 0L
45 | ): MutableList {
46 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
47 | return queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of(flags))
48 | @Suppress("DEPRECATION")
49 | return queryIntentActivities(intent, flags.toInt())
50 | }
51 |
52 | fun PackageManager.resolveActivityCompat(intent: Intent, flags: Long = 0L): ResolveInfo? {
53 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
54 | return resolveActivity(intent, PackageManager.ResolveInfoFlags.of(flags))
55 | @Suppress("DEPRECATION")
56 | return resolveActivity(intent, flags.toInt())
57 | }
58 |
59 | fun PackageManager.getActivityInfoCompat(
60 | componentName: ComponentName,
61 | flags: Long = 0L
62 | ): ActivityInfo? {
63 | try {
64 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
65 | return getActivityInfo(componentName, PackageManager.ComponentInfoFlags.of(flags))
66 | @Suppress("DEPRECATION")
67 | return getActivityInfo(componentName, flags.toInt())
68 | } catch (_: NameNotFoundException) {
69 | }
70 | return null
71 | }
72 |
73 | @Suppress("unused")
74 | object SystemUtils {
75 | /**
76 | * returns the label of the specified activity.
77 | * Will first try using the activityInfo, and then the path to it.
78 | */
79 | fun getActivityLabel(
80 | packageManager: PackageManager, packageName: String, inputActivityInfo: ActivityInfo?,
81 | fullPathToActivity: String?
82 | ): String? {
83 | var activityInfo: ActivityInfo? = inputActivityInfo
84 | var label: String? = null
85 | if (fullPathToActivity != null && activityInfo == null) {
86 | try {
87 | activityInfo =
88 | packageManager.getActivityInfoCompat(
89 | ComponentName(packageName, fullPathToActivity),
90 | 0
91 | )
92 | } catch (_: NameNotFoundException) {
93 | }
94 | }
95 | if (activityInfo != null) {
96 | label = activityInfo.loadLabel(packageManager).toString()
97 | }
98 | return label
99 | }
100 |
101 | fun isDevMode(context: Context) =
102 | Settings.Secure.getInt(
103 | context.contentResolver,
104 | Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
105 | 0
106 | ) != 0
107 |
108 | /** returns the max size of the heap, in bytes */
109 | private fun getMaxMemInBytes(): Long = Runtime.getRuntime().maxMemory()
110 |
111 | /** returns the currently free memory in bytes (of the heap) */
112 | private fun getAvailableMemInBytes(): Long {
113 | // find available memory
114 | val runtime = Runtime.getRuntime()
115 | val usedMem = runtime.totalMemory() - runtime.freeMemory()
116 | val maxHeapSize = runtime.maxMemory()
117 | return maxHeapSize - usedMem
118 | }
119 |
120 | @Throws(ArithmeticException::class)
121 | @JvmStatic
122 | fun getHeapMemStats(): String {
123 | val maxMemInBytes: Long = getMaxMemInBytes()
124 | val availableMemInBytes: Long = getAvailableMemInBytes()
125 | val usedMemInBytes: Long = maxMemInBytes - availableMemInBytes
126 | val usedMemInPercentage: Long = usedMemInBytes * 100 / maxMemInBytes
127 | try {
128 | return "used: " + StringsUtil.bytesIntoHumanReadable(usedMemInBytes, isMetric = false) + " / " +
129 | StringsUtil.bytesIntoHumanReadable(maxMemInBytes, isMetric = false) + " (" + usedMemInPercentage + "%)"
130 | } catch (e: java.lang.ArithmeticException) {
131 | //For some reason this occurs on some old devices (mostly Android 7)
132 | throw ArithmeticException("failed to format heap stats: maxMemInBytes:$maxMemInBytes availableMemInBytes:$availableMemInBytes usedMemInBytes:$usedMemInBytes usedMemInPercentage:$usedMemInPercentage $e")
133 | }
134 | }
135 |
136 | fun setAppComponentEnabled(context: Context, componentClass: Class<*>, enable: Boolean) {
137 | val pm = context.packageManager
138 | val enableFlag =
139 | if (enable) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
140 | pm.setComponentEnabledSetting(
141 | ComponentName(context, componentClass), enableFlag,
142 | PackageManager.DONT_KILL_APP
143 | )
144 | }
145 |
146 | @RequiresPermission(allOf = [android.Manifest.permission.WAKE_LOCK])
147 | fun wakeUp(activity: Activity) {
148 | @Suppress("DEPRECATION") activity.window.addFlags(
149 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
150 | )
151 | val power: PowerManager = activity.getSystemServiceCompat()
152 | val lock =
153 | power.newWakeLock(
154 | PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE,
155 | activity.packageName + ":wakeup!"
156 | )
157 | lock.acquire(1000)
158 | lock.release()
159 | }
160 |
161 | @RequiresPermission(allOf = [android.Manifest.permission.ACCESS_NETWORK_STATE])
162 | fun isNetworkAvailable(context: Context): Boolean {
163 | return try {
164 | val connectivityManager: ConnectivityManager = context.getSystemServiceCompat()
165 | connectivityManager.activeNetworkInfo?.isConnected == true
166 | } catch (e: Exception) {
167 | false
168 | }
169 | }
170 |
171 | /**
172 | * return the number of cores of the device.
173 | * based on : http://stackoverflow.com/a/10377934/878126
174 | */
175 | val coresCount: Int by lazy {
176 | return@lazy kotlin.runCatching {
177 | val dir = File("/sys/devices/system/cpu/")
178 | val files = dir.listFiles { pathname -> Pattern.matches("cpu[0-9]+", pathname.name) }
179 | max(1, files?.size ?: 1)
180 | }.getOrDefault(1)
181 | }
182 |
183 | // https://stackoverflow.com/a/21505193/878126
184 | val isProbablyRunningOnEmulator: Boolean by lazy {
185 | return@lazy (
186 | // Android SDK emulator
187 | Build.MANUFACTURER == "Google" && Build.BRAND == "google" &&
188 | ((Build.FINGERPRINT.startsWith("google/sdk_gphone_")
189 | && Build.FINGERPRINT.endsWith(":user/release-keys")
190 | && Build.PRODUCT.startsWith("sdk_gphone_")
191 | && Build.MODEL.startsWith("sdk_gphone_"))
192 | //alternative
193 | || (Build.FINGERPRINT.startsWith("google/sdk_gphone64_") && (Build.FINGERPRINT.endsWith(":userdebug/dev-keys")
194 | || (Build.FINGERPRINT.endsWith(":user/release-keys")) && Build.PRODUCT.startsWith("sdk_gphone64_")
195 | && Build.MODEL.startsWith("sdk_gphone64_")))
196 | //Google Play Games emulator https://play.google.com/googleplaygames https://developer.android.com/games/playgames/emulator#other-downloads
197 | || (Build.MODEL == "HPE device" &&
198 | Build.FINGERPRINT.startsWith("google/kiwi_") && Build.FINGERPRINT.endsWith(":user/release-keys")
199 | && Build.BOARD == "kiwi" && Build.PRODUCT.startsWith("kiwi_"))
200 | )
201 | //
202 | || Build.FINGERPRINT.startsWith("generic")
203 | || Build.FINGERPRINT.startsWith("unknown")
204 | || Build.MODEL.contains("google_sdk")
205 | || Build.MODEL.contains("Emulator")
206 | || Build.MODEL.contains("Android SDK built for x86")
207 | //bluestacks
208 | || "QC_Reference_Phone" == Build.BOARD && !"Xiaomi".equals(Build.MANUFACTURER, ignoreCase = true)
209 | //bluestacks
210 | || Build.MANUFACTURER.contains("Genymotion")
211 | || Build.HOST.startsWith("Build")
212 | //MSI App Player
213 | || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
214 | || Build.PRODUCT == "google_sdk"
215 | // another Android SDK emulator check
216 | || SystemProperties.getProp("ro.kernel.qemu") == "1")
217 | }
218 |
219 | /**@return true iff we've detected that MIUI OS has MIUI optimization enabled. Returns null when failed to detect anything about it*/
220 | @SuppressLint("PrivateApi")
221 | fun isMiuiOptimizationEnabled(): Boolean? {
222 | try {
223 | val miuiOptimizationEnabled: String =
224 | SystemProperties.getProp("persist.sys.miui_optimization")
225 | if (miuiOptimizationEnabled.isNotEmpty()) return miuiOptimizationEnabled == "true"
226 | val clazz = Class.forName("android.miui.AppOpsUtils")
227 | val isOptedOutOfMiuiOptimization = clazz.getMethod("isXOptMode").invoke(null) as Boolean
228 | return !isOptedOutOfMiuiOptimization
229 | } catch (e: Exception) {
230 | return null
231 | }
232 | }
233 |
234 | fun hasRootManagerSystemApp(context: Context): Boolean {
235 | val rootAppsPackageNames =
236 | arrayOf(
237 | "com.topjohnwu.magisk",
238 | "eu.chainfire.supersu",
239 | "com.koushikdutta.superuser",
240 | "com.noshufou.android.su",
241 | "me.phh.superuser"
242 | )
243 | rootAppsPackageNames.forEach { rootAppPackageName ->
244 | try {
245 | context.packageManager.getApplicationInfo(rootAppPackageName, 0)
246 | return true
247 | } catch (e: Exception) {
248 | }
249 | }
250 | return false
251 | }
252 |
253 | fun hasSuBinary(): Boolean {
254 | return try {
255 | findBinary("su")
256 | } catch (e: Exception) {
257 | e.printStackTrace()
258 | false
259 | }
260 | }
261 |
262 | private fun findBinary(binaryName: String): Boolean {
263 | val paths = System.getenv("PATH")
264 | if (!paths.isNullOrBlank()) {
265 | val systemPlaces: List = paths.split(":")
266 | return systemPlaces.firstOrNull { File(it, binaryName).exists() } != null
267 | }
268 | val places = arrayOf(
269 | "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/",
270 | "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/"
271 | )
272 | return places.firstOrNull { File(it, binaryName).exists() } != null
273 | }
274 |
275 | fun getPerformanceClassValue(): Int {
276 | return try {
277 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
278 | Build.VERSION.MEDIA_PERFORMANCE_CLASS
279 | else -1
280 | } catch (e: Throwable) {
281 | e.printStackTrace()
282 | -1
283 | }
284 | }
285 |
286 | fun getArchitecture() = kotlin.runCatching { System.getProperty("os.arch") }.getOrNull() ?: ""
287 |
288 | /**returns a list of all current locales, or null if not needed as there aren't at least 2 (if it's one, it's the default locale anyway).
289 | * @param haveFirstAsCurrentLocale when true, makes sure the first locale is also the default one. If not, it depends on what you've set as locale*/
290 | // https://stackoverflow.com/a/77000208/878126
291 | fun getLocalesList(haveFirstAsCurrentLocale: Boolean = true): ArrayList? {
292 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
293 | if (haveFirstAsCurrentLocale)
294 | return arrayListOf(Locale.getDefault())
295 | return null
296 | }
297 | val localeList = Resources.getSystem().configuration.locales
298 | if (localeList.size() <= 1)
299 | return null
300 | val defaultLocale =
301 | if (haveFirstAsCurrentLocale) Locale.getDefault()
302 | else null
303 | val result = ArrayList(localeList.size())
304 | if (defaultLocale != null)
305 | result.add(defaultLocale)
306 | for (i in 0 until localeList.size()) {
307 | val locale = localeList[i]!!
308 | if (locale == defaultLocale)
309 | continue
310 | result.add(locale)
311 | }
312 | return result
313 | }
314 |
315 |
316 | /**used for Admob test ads and constent testing:
317 | * Admob test ads usage :
318 | * https://developers.google.com/admob/android/test-ads
319 | *
320 | * val deviceIds = arrayListOf(AdRequest.DEVICE_ID_EMULATOR)
321 | * getDeviceHashedId(context)?.let { deviceIds.add(it) }
322 | * MobileAds.setRequestConfiguration(RequestConfiguration.Builder().setTestDeviceIds(deviceIds).build())
323 | *
324 | * ads consent testing:
325 | * https://developers.google.com/admob/android/privacy
326 | *
327 | * val debugSettings = ConsentDebugSettings.Builder(app)
328 | * .setDebugGeography(ConsentDebugSettings.DebugGeography....)
329 | * .addTestDeviceHashedId(getDeviceHashedId(app)!!)
330 | * .build()
331 | * */
332 | @SuppressLint("HardwareIds")
333 | fun getDeviceHashedId(context: Application): String? {
334 | val md5 = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
335 | try {
336 | val md = MessageDigest.getInstance("MD5")
337 | val array = md.digest(md5.toByteArray())
338 | val sb = StringBuilder()
339 | for (i in array.indices)
340 | sb.append(Integer.toHexString(array[i].toInt() and 0xFF or 0x100).substring(1, 3))
341 | // Log.d("AppLog", "getDeviceIdForAdMobTestAds:$sb")
342 | return "$sb".uppercase(Locale.ENGLISH)
343 | } catch (e: NoSuchAlgorithmException) {
344 | e.printStackTrace()
345 | }
346 | return null
347 | }
348 | }
349 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/ViewUtils.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.annotation.SuppressLint
4 | import android.graphics.drawable.Drawable
5 | import android.view.Gravity
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import android.widget.FrameLayout
9 | import android.widget.ImageView
10 | import android.widget.LinearLayout
11 | import android.widget.RatingBar
12 | import android.widget.TextView
13 | import android.widget.ViewAnimator
14 | import androidx.annotation.IdRes
15 | import androidx.annotation.IntDef
16 | import androidx.core.view.children
17 | import androidx.core.view.forEachIndexed
18 | import androidx.core.view.isVisible
19 | import com.google.android.material.badge.BadgeDrawable
20 | import com.google.android.material.badge.BadgeUtils
21 |
22 | // https://github.com/material-components/material-components-android/issues/3860#issuecomment-1822276005
23 | @androidx.annotation.OptIn(com.google.android.material.badge.ExperimentalBadgeUtils::class)
24 | fun BadgeDrawable.attachToView(anchor: View, customBadgeParent: FrameLayout?) {
25 | BadgeUtils.attachBadgeDrawable(this, anchor, customBadgeParent)
26 | anchor.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
27 | updateBadgeCoordinates(anchor, customBadgeParent)
28 | }
29 | }
30 |
31 | fun View?.removeFromParent() = (this?.parent as? ViewGroup?)?.removeView(this)
32 |
33 | fun ImageView.setImageDrawableOrHide(newDrawable: Drawable?,
34 | @ViewUtils.Visibility visibilityWhenEmpty: Int = View.GONE) {
35 | if (newDrawable == null) {
36 | visibility = visibilityWhenEmpty
37 | setImageDrawable(null)
38 | } else {
39 | isVisible = true
40 | setImageDrawable(newDrawable)
41 | }
42 | }
43 |
44 | fun RatingBar.setRatingOrHide(newRating: Float?, @ViewUtils.Visibility visibilityWhenEmpty: Int = View.GONE) {
45 | if (newRating == null) {
46 | visibility = visibilityWhenEmpty
47 | rating = 0f
48 | } else {
49 | isVisible = true
50 | rating = newRating
51 | }
52 | }
53 |
54 |
55 | fun TextView.setTextOrHide(textToSet: CharSequence?, @ViewUtils.Visibility visibilityWhenEmpty: Int = View.GONE) {
56 | if (textToSet.isNullOrEmpty()) {
57 | visibility = visibilityWhenEmpty
58 | text = null
59 | } else {
60 | isVisible = true
61 | text = textToSet
62 | }
63 | }
64 |
65 | fun ViewAnimator.setViewToSwitchTo(viewToSwitchTo: View, animate: Boolean = true): Boolean {
66 | if (currentView === viewToSwitchTo)
67 | return false
68 | this.forEachIndexed { i, view ->
69 | if (view != viewToSwitchTo)
70 | return@forEachIndexed
71 | if (animate)
72 | displayedChild = i
73 | else {
74 | val outAnimation = this.outAnimation
75 | val inAnimation = this.inAnimation
76 | this.inAnimation = null
77 | this.outAnimation = null
78 | displayedChild = i
79 | this.inAnimation = inAnimation
80 | this.outAnimation = outAnimation
81 | }
82 | return true
83 | }
84 | return false
85 | }
86 |
87 | fun ViewAnimator.setViewToSwitchTo(@IdRes viewIdToSwitchTo: Int, animate: Boolean = true): Boolean {
88 | if (currentView.id == viewIdToSwitchTo)
89 | return false
90 | this.forEachIndexed { i, view ->
91 | if (view.id != viewIdToSwitchTo)
92 | return@forEachIndexed
93 | if (animate)
94 | displayedChild = i
95 | else {
96 | val outAnimation = this.outAnimation
97 | val inAnimation = this.inAnimation
98 | this.inAnimation = null
99 | this.outAnimation = null
100 | displayedChild = i
101 | this.inAnimation = inAnimation
102 | this.outAnimation = outAnimation
103 | }
104 | return true
105 | }
106 | return false
107 | }
108 |
109 | object ViewUtils {
110 | @IntDef(View.VISIBLE, View.INVISIBLE, View.GONE)
111 | @Retention(AnnotationRetention.SOURCE)
112 | annotation class Visibility
113 |
114 | /**returns the location of the child view in a LinearLayout, using Gravity values
115 | * Fill - view takes entire space
116 | * no-gravity - view not found
117 | * center-vertical/horizontal - in the middle of multiple other views
118 | * the rest are quite obvious:top/bottom/left/right*/
119 | @SuppressLint("RtlHardcoded")
120 | fun findLocationOfChildInLinearLayout(childView: View, container: LinearLayout): Int {
121 | val childCount = container.children.count()
122 | if (childCount == 0)
123 | return Gravity.NO_GRAVITY
124 | if (childCount == 1) {
125 | if (container.children.first() == childView)
126 | return Gravity.FILL
127 | return Gravity.NO_GRAVITY
128 | }
129 | //handle cases of at least 2 children:
130 | if (container.orientation == LinearLayout.HORIZONTAL) {
131 | //horizontal
132 | for ((index, child) in container.children.withIndex()) {
133 | if (child != childView)
134 | continue
135 | val isLeftToRight = container.layoutDirection == View.LAYOUT_DIRECTION_LTR
136 | // TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_LTR
137 | return when (index) {
138 | 0 -> {
139 | if (isLeftToRight) Gravity.LEFT else Gravity.RIGHT
140 | }
141 |
142 | childCount - 1 -> {
143 | if (isLeftToRight) Gravity.RIGHT else Gravity.LEFT
144 | }
145 |
146 | else -> Gravity.CENTER_HORIZONTAL
147 | }
148 | }
149 | return Gravity.FILL
150 | }
151 | else {
152 | //vertical
153 | for ((index, child) in container.children.withIndex()) {
154 | if (child != childView)
155 | continue
156 | return when (index) {
157 | 0 -> Gravity.TOP
158 | childCount - 1 -> Gravity.BOTTOM
159 | else -> Gravity.CENTER_VERTICAL
160 | }
161 | }
162 | }
163 | return Gravity.NO_GRAVITY
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/WorkerManagerUtils.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils
2 |
3 | import android.content.Context
4 | import androidx.annotation.AnyThread
5 | import androidx.annotation.WorkerThread
6 | import androidx.work.OneTimeWorkRequest
7 | import androidx.work.WorkInfo
8 | import androidx.work.WorkManager
9 | import androidx.work.Worker
10 | import androidx.work.WorkerParameters
11 | import java.util.concurrent.TimeUnit
12 |
13 | /**reason to use this: https://issuetracker.google.com/issues/115575872 https://commonsware.com/blog/2018/11/24/workmanager-app-widgets-side-effects.html*/
14 | object WorkerManagerUtils {
15 | fun interface OnGotWorkerManager {
16 | @WorkerThread
17 | fun onGotWorkerManager(workerManager: WorkManager)
18 | }
19 |
20 | @WorkerThread
21 | fun getWorkerManager(context: Context, onGotWorkerManager: OnGotWorkerManager) {
22 | val workManager = WorkManager.getInstance(context)
23 | val dummyWorkers = workManager.getWorkInfosByTag(DummyWorker.DUMMY_WORKER_TAG).get()
24 | val hasPendingDummyWorker =
25 | (dummyWorkers?.indexOfFirst { it.state == WorkInfo.State.ENQUEUED || it.state == WorkInfo.State.RUNNING } ?: -1) >= 0
26 | if (!hasPendingDummyWorker) {
27 | DummyWorker.schedule(context)
28 | }
29 | onGotWorkerManager.onGotWorkerManager(workManager)
30 | }
31 |
32 | class DummyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
33 | override fun doWork(): Result {
34 | schedule(applicationContext)
35 | return Result.success()
36 | }
37 |
38 | companion object {
39 | const val DUMMY_WORKER_TAG = "DummyWorker"
40 |
41 | @AnyThread
42 | fun schedule(context: Context) {
43 | WorkManager.getInstance(context).enqueue(OneTimeWorkRequest.Builder(
44 | DummyWorker::class.java).addTag(DUMMY_WORKER_TAG).setInitialDelay(10L * 365L, TimeUnit.DAYS)
45 | .build())
46 | }
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/custom_views/CheckBox.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils.custom_views
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import com.google.android.material.checkbox.MaterialCheckBox
6 |
7 | //https://stackoverflow.com/a/27391245/878126
8 | class CheckBox : MaterialCheckBox {
9 | private var listener: OnCheckedChangeListener? = null
10 |
11 | constructor(context: Context?) : super(context)
12 | constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
13 | constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
14 |
15 | override fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
16 | this.listener = listener
17 | super.setOnCheckedChangeListener(listener)
18 | }
19 |
20 | fun setChecked(checked: Boolean, alsoNotify: Boolean) {
21 | if (!alsoNotify) {
22 | super.setOnCheckedChangeListener(null)
23 | super.setChecked(checked)
24 | super.setOnCheckedChangeListener(listener)
25 | return
26 | }
27 | super.setChecked(checked)
28 | }
29 |
30 | fun toggle(alsoNotify: Boolean) {
31 | if (!alsoNotify) {
32 | super.setOnCheckedChangeListener(null)
33 | super.toggle()
34 | super.setOnCheckedChangeListener(listener)
35 | return
36 | }
37 | super.toggle()
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/custom_views/GridLayoutManagerEx.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils.custom_views
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import androidx.recyclerview.widget.GridLayoutManager
6 |
7 | //https://stackoverflow.com/a/33985508/878126
8 | class GridLayoutManagerEx : GridLayoutManager {
9 | constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
10 | constructor(context: Context, spanCount: Int) : super(context, spanCount)
11 | constructor(context: Context, spanCount: Int, orientation: Int, reverseLayout: Boolean) : super(context, spanCount, orientation, reverseLayout)
12 |
13 | override fun supportsPredictiveItemAnimations(): Boolean {
14 | return false
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/custom_views/LinearLayoutManagerEx.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils.custom_views
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import androidx.recyclerview.widget.LinearLayoutManager
6 |
7 | //https://stackoverflow.com/a/33985508/878126
8 | class LinearLayoutManagerEx : LinearLayoutManager {
9 | constructor(context: Context) : super(context)
10 | constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
11 | constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
12 |
13 | override fun supportsPredictiveItemAnimations(): Boolean {
14 | return false
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/custom_views/WebViewContainer.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils.custom_views
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.view.ViewGroup
6 | import android.webkit.WebView
7 | import android.widget.FrameLayout
8 |
9 | /**workaround for this: https://issuetracker.google.com/issues/133390434 */
10 | class WebViewContainer : FrameLayout {
11 | @Suppress("MemberVisibilityCanBePrivate")
12 | val webView: WebView = try {
13 | WebView(context)
14 | } catch (e: Exception) {
15 | e.printStackTrace()
16 | WebView(context.applicationContext)
17 | }
18 |
19 | constructor(context: Context) : super(context)
20 | constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
21 | constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
22 |
23 | init {
24 | addView(webView, LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
25 | //TODO in case of dark theme requirement, consider telling the WebView to also support it:
26 | //IMPORTANT: This seems to force dark theme, even if the webpage isn't ready.
27 | // https://joebirch.co/2020/01/24/enabling-dark-theme-in-android-webviews/
28 | // if (context.isCurrentlyOnDarkTheme() && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK))
29 | // WebSettingsCompat.setForceDark(webView.settings, WebSettingsCompat.FORCE_DARK_ON)
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/toast/SafeToastContext.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils.toast
2 |
3 | import android.content.Context
4 | import android.content.ContextWrapper
5 | import android.view.Display
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import android.view.WindowManager
9 | import android.widget.Toast
10 |
11 | /**
12 | * @author drakeet
13 | */
14 | internal class SafeToastContext(base: Context, private val toast: Toast) : ContextWrapper(base) {
15 | override fun getApplicationContext(): Context {
16 | return ApplicationContextWrapper(baseContext.applicationContext)
17 | }
18 |
19 | private inner class ApplicationContextWrapper constructor(base: Context) :
20 | ContextWrapper(base) {
21 | override fun getSystemService(name: String): Any {
22 | return if (WINDOW_SERVICE == name) {
23 | WindowManagerWrapper(baseContext.getSystemService(name) as WindowManager)
24 | } else super.getSystemService(name)
25 | }
26 | }
27 |
28 | private inner class WindowManagerWrapper constructor(private val base: WindowManager) :
29 | WindowManager {
30 | @Deprecated("Deprecated in Java")
31 | override fun getDefaultDisplay(): Display {
32 | return base.defaultDisplay
33 | }
34 |
35 | override fun removeViewImmediate(view: View) {
36 | base.removeViewImmediate(view)
37 | }
38 |
39 | override fun addView(view: View, params: ViewGroup.LayoutParams) {
40 | try {
41 | base.addView(view, params)
42 | } catch (throwable: Throwable) {
43 | throwable.printStackTrace()
44 | }
45 | }
46 |
47 | override fun updateViewLayout(view: View, params: ViewGroup.LayoutParams) {
48 | base.updateViewLayout(view, params)
49 | }
50 |
51 | override fun removeView(view: View) {
52 | base.removeView(view)
53 | }
54 |
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/library/src/main/java/com/lb/common_utils/toast/ToastCompat.kt:
--------------------------------------------------------------------------------
1 | package com.lb.common_utils.toast
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.Context
5 | import android.content.res.Resources.NotFoundException
6 | import android.os.Build
7 | import android.view.View
8 | import android.widget.Toast
9 | import androidx.annotation.StringRes
10 |
11 | /**
12 | * @author drakeet
13 | */
14 | class ToastCompat
15 | /**
16 | * Construct an empty Toast object. You must call [.setView] before you
17 | * can call [.show].
18 | *
19 | * @param context The context to use. Usually your [Application]
20 | * or [Activity] object.
21 | * @param base The base toast
22 | */
23 | private constructor(context: Context, val baseToast: Toast) : Toast(context) {
24 | override fun show() {
25 | baseToast.show()
26 | }
27 |
28 | override fun setDuration(duration: Int) {
29 | baseToast.duration = duration
30 | }
31 |
32 | override fun setGravity(gravity: Int, xOffset: Int, yOffset: Int) {
33 | baseToast.setGravity(gravity, xOffset, yOffset)
34 | }
35 |
36 | override fun setMargin(horizontalMargin: Float, verticalMargin: Float) {
37 | baseToast.setMargin(horizontalMargin, verticalMargin)
38 | }
39 |
40 | override fun setText(resId: Int) {
41 | baseToast.setText(resId)
42 | }
43 |
44 | override fun setText(s: CharSequence) {
45 | baseToast.setText(s)
46 | }
47 |
48 | @Deprecated("Deprecated in Java")
49 | override fun setView(view: View) {
50 | baseToast.view = view
51 | setContextCompat(view, SafeToastContext(view.context, this))
52 | }
53 |
54 | override fun getHorizontalMargin(): Float {
55 | return baseToast.horizontalMargin
56 | }
57 |
58 | override fun getVerticalMargin(): Float {
59 | return baseToast.verticalMargin
60 | }
61 |
62 | override fun getDuration(): Int {
63 | return baseToast.duration
64 | }
65 |
66 | override fun getGravity(): Int {
67 | return baseToast.gravity
68 | }
69 |
70 | override fun getXOffset(): Int {
71 | return baseToast.xOffset
72 | }
73 |
74 | override fun getYOffset(): Int {
75 | return baseToast.yOffset
76 | }
77 |
78 | @Deprecated("Deprecated in Java")
79 | override fun getView(): View? {
80 | return baseToast.view
81 | }
82 |
83 | companion object {
84 | /**
85 | * Make a standard toast that just contains a text view.
86 | *
87 | * @param context The context to use. Usually your [android.app.Application]
88 | * or [android.app.Activity] object.
89 | * @param text The text to show. Can be formatted text.
90 | * @param duration How long to display the message. Either [.LENGTH_SHORT] or
91 | * [.LENGTH_LONG]
92 | */
93 | fun makeText(context: Context, text: CharSequence?, duration: Int): Toast {
94 | if (Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1)
95 | return Toast.makeText(context, text, duration)
96 | // We cannot pass the SafeToastContext to Toast.makeText() because
97 | // the View will unwrap the base context and we are in vain.
98 | @SuppressLint("ShowToast") val toast = Toast.makeText(context, text, duration)
99 | setContextCompat(toast.view!!, SafeToastContext(context, toast))
100 | return ToastCompat(context, toast)
101 | }
102 |
103 | /**
104 | * Make a standard toast that just contains a text view with the text from a resource.
105 | *
106 | * @param context The context to use. Usually your [android.app.Application]
107 | * or [android.app.Activity] object.
108 | * @param resId The resource id of the string resource to use. Can be formatted text.
109 | * @param duration How long to display the message. Either [.LENGTH_SHORT] or
110 | * [.LENGTH_LONG]
111 | * @throws Resources.NotFoundException if the resource can't be found.
112 | */
113 | @Throws(NotFoundException::class)
114 | fun makeText(context: Context, @StringRes resId: Int, duration: Int): Toast {
115 | if (Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1)
116 | return Toast.makeText(context, resId, duration)
117 | return makeText(context, context.resources.getText(resId), duration)
118 | }
119 |
120 | private fun setContextCompat(view: View, context: Context) {
121 | if (Build.VERSION.SDK_INT == 25) {
122 | try {
123 | @SuppressLint("DiscouragedPrivateApi") val field =
124 | View::class.java.getDeclaredField("mContext")
125 | field.isAccessible = true
126 | field[view] = context
127 | } catch (throwable: Throwable) {
128 | throwable.printStackTrace()
129 | }
130 | }
131 | }
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = "CommonUtils"
2 | include ':app'
3 | include ':library'
4 |
--------------------------------------------------------------------------------