├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── styles.xml
│ │ │ └── colors.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── layout
│ │ │ ├── item_type0.xml
│ │ │ ├── activity_sigle1.xml
│ │ │ ├── activity_sigle2.xml
│ │ │ ├── activity_multi1.xml
│ │ │ ├── activity_multi2.xml
│ │ │ ├── item_sigle1.xml
│ │ │ ├── item_sigle2.xml
│ │ │ ├── item_type1.xml
│ │ │ └── activity_main.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ └── kt
│ │ │ └── ktbindadapter
│ │ │ ├── bean
│ │ │ └── ItemInfo.kt
│ │ │ ├── MainActivity.kt
│ │ │ ├── Sigle1Activity.kt
│ │ │ ├── Multi1Activity.kt
│ │ │ ├── Sigle2Activity.kt
│ │ │ └── Multi2Activity.kt
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── ktTool
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ └── attrs.xml
│ │ ├── drawable-xxhdpi
│ │ │ ├── toast_frame.9.png
│ │ │ ├── ic_check_white_48dp.png
│ │ │ ├── ic_clear_white_48dp.png
│ │ │ ├── ic_info_outline_white_48dp.png
│ │ │ ├── ic_error_outline_white_48dp.png
│ │ │ └── shape_round_white.xml
│ │ ├── hdpi-drawable
│ │ │ ├── ic_check_white_48dp.png
│ │ │ ├── ic_clear_white_48dp.png
│ │ │ ├── ic_info_outline_white_48dp.png
│ │ │ └── ic_error_outline_white_48dp.png
│ │ └── layout
│ │ │ ├── dia_base_bottom.xml
│ │ │ ├── toast_layout.xml
│ │ │ ├── view_error.xml
│ │ │ ├── view_empty.xml
│ │ │ ├── view_no_network.xml
│ │ │ ├── view_loding.xml
│ │ │ └── dia_t.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── tgs
│ │ └── kttool
│ │ ├── util
│ │ ├── IntExt.kt
│ │ ├── AnyExt.kt
│ │ ├── BooleanExt.kt
│ │ ├── AppUtil.kt
│ │ ├── StringExt.kt
│ │ ├── GlideCircleTransform.java
│ │ ├── ViewExt.kt
│ │ ├── SPUtil.kt
│ │ ├── ViewBindingAdapter.kt
│ │ ├── DateUtil.kt
│ │ ├── FileUtil.kt
│ │ └── ToastUtil.kt
│ │ ├── ToolConfigs.kt
│ │ ├── ToolApplication.kt
│ │ └── view
│ │ ├── BindEditText.kt
│ │ ├── BaseBottomDia.kt
│ │ ├── TDialog.kt
│ │ ├── RotateLoading.java
│ │ └── LoadView.kt
├── proguard-rules.pro
└── build.gradle
├── ktAdapter
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ └── strings.xml
│ │ └── layout
│ │ │ └── item_test.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── tgs
│ │ └── adapter
│ │ ├── BindViewHolder.kt
│ │ ├── MultiItem.kt
│ │ ├── SimpleMultiAdapter.kt
│ │ ├── SimpleAdapter.kt
│ │ ├── BaseSigleAdapter.kt
│ │ ├── BaseMultiAdapter.kt
│ │ └── BaseAdapter.kt
├── build.gradle
└── proguard-rules.pro
├── githubGreen-csharp.txt
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README.md
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/ktTool/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/ktAdapter/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/githubGreen-csharp.txt:
--------------------------------------------------------------------------------
1 | 2019/7/12-4
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':ktAdapter', ':ktTool'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | KtBindAdapter
3 |
4 |
--------------------------------------------------------------------------------
/ktTool/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | KtTool
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/ktAdapter/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BindAdapter
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ktAdapter/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/drawable-xxhdpi/toast_frame.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/drawable-xxhdpi/toast_frame.9.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/drawable-xxhdpi/ic_check_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/drawable-xxhdpi/ic_check_white_48dp.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/drawable-xxhdpi/ic_clear_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/drawable-xxhdpi/ic_clear_white_48dp.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/hdpi-drawable/ic_check_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/hdpi-drawable/ic_check_white_48dp.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/hdpi-drawable/ic_clear_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/hdpi-drawable/ic_clear_white_48dp.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 | /.idea
--------------------------------------------------------------------------------
/ktTool/src/main/res/hdpi-drawable/ic_info_outline_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/hdpi-drawable/ic_info_outline_white_48dp.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/drawable-xxhdpi/ic_info_outline_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/drawable-xxhdpi/ic_info_outline_white_48dp.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/hdpi-drawable/ic_error_outline_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/hdpi-drawable/ic_error_outline_white_48dp.png
--------------------------------------------------------------------------------
/ktTool/src/main/res/drawable-xxhdpi/ic_error_outline_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TianGuisen/KtBindAdapter/HEAD/ktTool/src/main/res/drawable-xxhdpi/ic_error_outline_white_48dp.png
--------------------------------------------------------------------------------
/app/src/main/java/kt/ktbindadapter/bean/ItemInfo.kt:
--------------------------------------------------------------------------------
1 | package kt.ktbindadapter.bean
2 |
3 | class ItemInfo(var name: String?, var age: Int) {
4 |
5 | override fun toString(): String {
6 | return "ItemInfo(name=$name, age=$age)"
7 | }
8 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/ktAdapter/src/main/java/tgs/adapter/BindViewHolder.kt:
--------------------------------------------------------------------------------
1 | package kt.ktbindadapter.baseAdapter
2 |
3 | import android.support.v7.widget.RecyclerView
4 | import android.view.View
5 |
6 | class BindViewHolder(itemView: View, val binding: VB) : RecyclerView.ViewHolder(itemView)
--------------------------------------------------------------------------------
/ktAdapter/src/main/java/tgs/adapter/MultiItem.kt:
--------------------------------------------------------------------------------
1 | package tgs.adapter
2 |
3 | /**
4 | * 多type的需要用这个包装实体类
5 | */
6 | class MultiItem(var itemType: Int, var data: T) {
7 | override fun toString(): String {
8 | return "MultiItem(itemType=$itemType, data=$data)"
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/ktTool/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/IntExt.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import tgs.kttool.ToolApplication.toolAppContext
4 |
5 |
6 | fun Int.dp2px() = (toolAppContext.getResources().getDisplayMetrics().density * this + 0.5).toInt()
7 |
8 | fun Int.px2dp() = (this / (toolAppContext.getResources().getDisplayMetrics().density) + 0.5).toInt()
9 |
--------------------------------------------------------------------------------
/ktTool/src/main/res/drawable-xxhdpi/shape_round_white.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/ToolConfigs.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool
2 |
3 | object ToolConfigs {
4 | //在Bugly上创建2个应用,一个用于测试一个用于线上,避免搞不清楚出的bug是测试测出的bug还是线上bug
5 | const val BUGLY_APPID_RELEASE = "9658217cfb"
6 | const val BUGLY_APPID_DEBUG = "abc"
7 | /**
8 | * Logger日志的tag
9 | */
10 | const val LOGGER_TAG = "tian"
11 | /**
12 | * Logger网络请求日志的tag
13 | */
14 | const val LOGGER_NET_TAG = "retrofit"
15 |
16 |
17 | }
--------------------------------------------------------------------------------
/ktAdapter/src/main/res/layout/item_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
10 |
11 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/ktTool/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/ktAdapter/src/main/java/tgs/adapter/SimpleMultiAdapter.kt:
--------------------------------------------------------------------------------
1 | package tgs.adapter
2 |
3 | import android.databinding.ViewDataBinding
4 | import kt.ktbindadapter.baseAdapter.BindViewHolder
5 |
6 | /**
7 | * Created by 田桂森 on 2017/8/18.
8 | * 多type如果不需要设置item中子类子类点击事件用这个
9 | */
10 | class SimpleMultiAdapter(datas: MutableList>) : BaseMultiAdapter(datas) {
11 | override fun decorator(bean: MultiItem, holder: BindViewHolder, position: Int) {
12 |
13 | }
14 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/ktAdapter/src/main/java/tgs/adapter/SimpleAdapter.kt:
--------------------------------------------------------------------------------
1 | package tgs.adapter
2 |
3 | import android.databinding.ViewDataBinding
4 | import kt.ktbindadapter.baseAdapter.BindViewHolder
5 |
6 | /**
7 | * Created by 田桂森 on 2017/8/17.
8 | * 如果不需要设置item中子类点击事件用这个
9 | */
10 |
11 | class SimpleAdapter(datas: MutableList, layoutId: Int) : BaseSigleAdapter(datas, layoutId) {
12 | override fun decorator(bean: E, holder: BindViewHolder, position: Int) {
13 |
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ktAdapter/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'com.github.dcendents.android-maven'
4 | group='com.github.TianGuisen'
5 | kotlin {
6 | experimental {
7 | coroutines "enable"
8 | }
9 | }
10 | android {
11 | compileSdkVersion 27
12 | defaultConfig {
13 | minSdkVersion 15
14 | targetSdkVersion 27
15 | }
16 | dataBinding {
17 | enabled = true
18 | }
19 |
20 | }
21 |
22 | dependencies {
23 | implementation 'com.android.support:recyclerview-v7:27.1.1'
24 | }
25 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/AnyExt.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import android.app.Activity
4 | import android.content.Intent
5 | import android.icu.lang.UCharacter.GraphemeClusterBreak.T
6 | import com.alibaba.fastjson.JSON
7 |
8 | fun Any.toJson(): String = JSON.toJSONString(this)
9 |
10 | /**
11 | * 获取泛型的.class
12 | * 以reified修饰类型后,就能够在函数内部使用相关类型。
13 | */
14 | inline fun classOf() = T::class.java
15 |
16 | //以reified修饰类型后,就能够在函数内部使用相关类型。
17 | private inline fun Activity.startActivity() {
18 | startActivity(Intent(this, T::class.java))
19 | }
--------------------------------------------------------------------------------
/ktTool/src/main/res/layout/dia_base_bottom.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_type0.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FB7299
4 | #FA7199
5 | #FA7199
6 | #FDC5D5
7 | #fff
8 | #555555
9 | #FFFFD11D
10 | #99AAAAAA
11 | #FFFFFF
12 | #66BABABA
13 | #FF797979
14 | #00f
15 |
--------------------------------------------------------------------------------
/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=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
15 |
--------------------------------------------------------------------------------
/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
22 |
--------------------------------------------------------------------------------
/ktTool/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
22 |
--------------------------------------------------------------------------------
/ktAdapter/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
22 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/BooleanExt.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util;
2 |
3 | /**
4 | * 其实实用性不大,练习泛型和枚举类
5 | */
6 | sealed class BooleanExt
7 |
8 | object Otherwise : BooleanExt()
9 | class WithData(val data:T) : BooleanExt()
10 |
11 | inline fun Boolean.yes(function: () -> T): BooleanExt = when {
12 | true -> {
13 | WithData(function())
14 | }
15 | else -> {
16 | Otherwise
17 | }
18 |
19 | }
20 |
21 |
22 | inline fun Boolean.no(function: () -> T): BooleanExt = when {
23 | true -> {
24 | Otherwise
25 | }
26 | else -> {
27 | WithData(function())
28 | }
29 | }
30 |
31 | @Suppress("UNCHECKED_CAST")
32 | inline fun BooleanExt.otherwise(function: () -> T): T = when (this) {
33 | is Otherwise -> function()
34 | is WithData -> this.data
35 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_sigle1.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_sigle2.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_multi1.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_multi2.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_sigle1.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
10 |
11 |
18 |
19 |
26 |
27 |
--------------------------------------------------------------------------------
/ktTool/src/main/res/layout/toast_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
15 |
16 |
20 |
21 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/ToolApplication.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool
2 |
3 | import android.app.Application
4 | import com.orhanobut.logger.AndroidLogAdapter
5 | import com.orhanobut.logger.Logger
6 | import com.orhanobut.logger.PrettyFormatStrategy
7 | import kt.ktbindadapter.BuildConfig
8 |
9 |
10 | object ToolApplication {
11 | lateinit var toolAppContext: Application
12 | fun init(appContext: Application) {
13 | toolAppContext = appContext
14 | val strategy = PrettyFormatStrategy.newBuilder()
15 | .showThreadInfo(false) // 是否显示线程信息,默认为ture
16 | .methodCount(1) // 显示的方法行数
17 | .methodOffset(0) // 隐藏内部方法调用到偏移量
18 | .tag(ToolConfigs.LOGGER_TAG)
19 | .build()
20 | Logger.addLogAdapter(object : AndroidLogAdapter(strategy) {
21 | override fun isLoggable(priority: Int, tag: String?): Boolean {
22 | return BuildConfig.DEBUG
23 | }
24 | })
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_sigle2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
10 |
11 |
18 |
19 |
25 |
26 |
32 |
33 |
--------------------------------------------------------------------------------
/ktTool/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | apply plugin: 'kotlin-kapt'
5 | kotlin {
6 | experimental {
7 | coroutines "enable"
8 | }
9 | androidExtensions {
10 | experimental = true
11 | }
12 | }
13 | android {
14 | compileSdkVersion 27
15 |
16 | defaultConfig {
17 | minSdkVersion 15
18 | targetSdkVersion 27
19 | }
20 | dataBinding {
21 | enabled = true
22 | }
23 | }
24 |
25 | dependencies {
26 | //log日志
27 | api 'com.orhanobut:logger:2.2.0'
28 | //只能使用特定版本,最新版不支持kotlin
29 | api 'com.alibaba:fastjson:1.1.61.android'
30 | api 'com.android.support:support-v4:27.1.1'
31 | //下拉刷新https://github.com/scwang90/SmartRefreshLayout/blob/master/art/md_property.md
32 | api 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-alpha-7'
33 | api 'com.github.bumptech.glide:glide:4.7.1'
34 | api 'com.android.support:design:27.1.1'
35 | api 'com.android.support.constraint:constraint-layout:1.1.3'
36 | }
37 |
--------------------------------------------------------------------------------
/ktTool/src/main/res/layout/view_error.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
24 |
--------------------------------------------------------------------------------
/ktTool/src/main/res/layout/view_empty.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
24 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/AppUtil.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import android.content.Context
4 | import android.net.ConnectivityManager
5 | import android.net.NetworkInfo
6 | import android.provider.Settings
7 | import android.support.v4.content.ContextCompat
8 | import tgs.kttool.ToolApplication.toolAppContext
9 |
10 | object AppUtil {
11 |
12 | /**
13 | * 网络是否链接
14 | */
15 | fun isConnected(): Boolean {
16 | (toolAppContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo.also {
17 | if (null != it && it.isConnected) {
18 | if (it.state == NetworkInfo.State.CONNECTED) {
19 | return true
20 | }
21 | }
22 | }
23 | return false
24 | }
25 |
26 | /**
27 | * 获得values里的colors
28 | */
29 | fun getColor(colorId: Int) = ContextCompat.getColor(toolAppContext, colorId)
30 |
31 | /**
32 | * 设备id
33 | */
34 | val deviceId: String
35 | get() = Settings.Secure.getString(toolAppContext.contentResolver, Settings.Secure.ANDROID_ID)
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/app/src/main/java/kt/ktbindadapter/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package kt.ktbindadapter
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import android.view.View
7 |
8 | class MainActivity : AppCompatActivity() {
9 |
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 | setContentView(R.layout.activity_main)
13 | findViewById(R.id.tv1).setOnClickListener {
14 | MainActivity@ this.startActivity(Intent(MainActivity@ this, Sigle1Activity::class.java))
15 | }
16 | findViewById(R.id.tv2).setOnClickListener {
17 | MainActivity@ this.startActivity(Intent(MainActivity@ this, Sigle2Activity::class.java))
18 | }
19 | findViewById(R.id.tv3).setOnClickListener {
20 | MainActivity@ this.startActivity(Intent(MainActivity@ this, Multi1Activity::class.java))
21 | }
22 | findViewById(R.id.tv4).setOnClickListener {
23 | MainActivity@ this.startActivity(Intent(MainActivity@ this, Multi2Activity::class.java))
24 | }
25 |
26 | }
27 | }
--------------------------------------------------------------------------------
/ktTool/src/main/res/layout/view_no_network.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
25 |
--------------------------------------------------------------------------------
/ktTool/src/main/res/layout/view_loding.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_type1.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
10 |
11 |
17 |
18 |
26 |
27 |
35 |
36 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/view/BindEditText.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.view
2 |
3 | import android.content.Context
4 | import android.graphics.Rect
5 | import android.util.AttributeSet
6 |
7 | /**
8 | * Created by 田桂森 on 2017/7/27.
9 | * 实现了使用ObservableBoolean监听和控制edittext的焦点。
10 | * 使用editText无法实现这个功能,这是自定义双向绑定.
11 | * bind:focus="@={vm.?}"
12 | */
13 |
14 | class BindEditText : android.support.v7.widget.AppCompatEditText {
15 |
16 | private var onFocusChangedListener: OnFocusChangedListener? = null
17 |
18 | constructor(context: Context) : super(context) {}
19 |
20 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
21 |
22 |
23 | constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
24 |
25 | override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
26 | super.onFocusChanged(focused, direction, previouslyFocusedRect)
27 | onFocusChangedListener?.onChanged()
28 | }
29 |
30 | fun setListener(onFocusChangedListener: OnFocusChangedListener) {
31 | this.onFocusChangedListener = onFocusChangedListener
32 | }
33 |
34 | interface OnFocusChangedListener {
35 | fun onChanged()
36 | }
37 |
38 | }
--------------------------------------------------------------------------------
/app/src/main/java/kt/ktbindadapter/Sigle1Activity.kt:
--------------------------------------------------------------------------------
1 | package kt.ktbindadapter
2 |
3 | import android.databinding.ObservableArrayList
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import android.support.v7.widget.DividerItemDecoration
7 | import kotlinx.android.synthetic.main.activity_sigle1.*
8 | import tgs.adapter.SimpleAdapter
9 | import kt.ktbindadapter.bean.ItemInfo
10 | import tgs.kttool.util.ToastUtil
11 |
12 | class Sigle1Activity : AppCompatActivity() {
13 | val listData = ObservableArrayList()
14 |
15 | init {
16 | for (i1 in 0..9) {
17 | listData.add(ItemInfo("name" + i1, i1))
18 | }
19 |
20 | }
21 |
22 | override fun onCreate(savedInstanceState: Bundle?) {
23 | super.onCreate(savedInstanceState)
24 | setContentView(R.layout.activity_sigle1)
25 | //最普通的,直接创建SimpleAdapter即可,没有item子view的点击事件
26 | val testAdapter = SimpleAdapter(listData, R.layout.item_sigle1)
27 | rv.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
28 | rv.setAdapter(testAdapter)
29 |
30 | testAdapter.setOnItemClickLisener { itemInfo, view, i ->
31 | ToastUtil.normal("点击的是item" + itemInfo)
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | apply plugin: 'kotlin-kapt'
5 | kotlin {
6 | experimental {
7 | coroutines "enable"
8 | }
9 | androidExtensions {
10 | experimental = true
11 | }
12 | }
13 | android {
14 | compileSdkVersion 27
15 | defaultConfig {
16 | applicationId "kt.ktbindadapter"
17 | minSdkVersion 15
18 | targetSdkVersion 27
19 | versionCode 1
20 | versionName "1.0"
21 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
22 | multiDexEnabled true
23 | }
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
28 | }
29 | }
30 | dataBinding {
31 | enabled = true
32 | }
33 | compileOptions {
34 | targetCompatibility 1.8
35 | sourceCompatibility 1.8
36 | }
37 | }
38 |
39 | dependencies {
40 | implementation 'com.android.support:appcompat-v7:27.1.1'
41 | implementation 'com.android.support:recyclerview-v7:27.1.1'
42 | implementation project(path: ':ktAdapter')
43 | implementation project(path: ':ktTool')
44 | }
45 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/StringExt.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import com.alibaba.fastjson.JSON
4 |
5 | /**
6 | * 获取最后位置的字符串
7 | */
8 | fun String.lastStr(): String = this.get(this.length - 1).toString()
9 |
10 | fun String.fromJson(clazz: Class) = JSON.parseObject(this, clazz)
11 |
12 | inline fun String.fromJson() = JSON.parseObject(this, T::class.java)
13 | /**
14 | * 获取后面i个字符串
15 | */
16 | fun String.subEnd(i: Int) = this.substring(this.length - i)
17 |
18 | /**
19 | * 获取前面i个字符串
20 | */
21 | fun String.subStart(i: Int) = this.substring(0, i)
22 |
23 | /**
24 | * 对字符加星号处理:除前面几位和后面几位外,其他的字符以星号代替
25 | *
26 | * @param content 传入的字符串
27 | * @param frontNum 保留前面字符的位数
28 | * @param endNum 保留后面字符的位数
29 | */
30 | fun String.getStarStr(content: String, frontNum: Int, endNum: Int): String {
31 |
32 | if (frontNum >= content.length || frontNum < 0) {
33 | return content
34 | }
35 | if (endNum >= content.length || endNum < 0) {
36 | return content
37 | }
38 | if (frontNum + endNum >= content.length) {
39 | return content
40 | }
41 | var starStr = ""
42 | for (i in 0 until content.length - frontNum - endNum) {
43 | starStr = "$starStr*"
44 | }
45 | return (content.substring(0, frontNum) + starStr + content.substring(content.length - endNum, content.length))
46 |
47 | }
--------------------------------------------------------------------------------
/ktAdapter/src/main/java/tgs/adapter/BaseSigleAdapter.kt:
--------------------------------------------------------------------------------
1 | package tgs.adapter
2 |
3 | import android.databinding.DataBindingUtil
4 | import android.databinding.ViewDataBinding
5 | import android.view.LayoutInflater
6 | import android.view.ViewGroup
7 | import kt.ktbindadapter.baseAdapter.BindViewHolder
8 |
9 | /**
10 | * 单type
11 | * 如果item内容填充较复杂,无法在item的xml中完成,需要在decorator完成填充,就使用这个
12 | * 或者需要子view的点击事件使用这个
13 | */
14 | abstract class BaseSigleAdapter : BaseAdapter {
15 |
16 | private var layoutId: Int = 0
17 |
18 | constructor(datas: MutableList, layoutId: Int) : super(datas) {
19 | this.layoutId = layoutId
20 | }
21 |
22 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindViewHolder {
23 | val binding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), layoutId, parent, false)
24 | return BindViewHolder(binding.root, binding)
25 | }
26 |
27 | fun add(data: E) {
28 | mDatas.add(data)
29 | notifyDataSetChanged()
30 | }
31 |
32 | fun add(position: Int, data: E) {
33 | mDatas.add(position, data)
34 | notifyDataSetChanged()
35 | }
36 |
37 | fun set(data: List) {
38 | mDatas.clear()
39 | addAll(data)
40 | }
41 |
42 | fun addAll(data: List) {
43 | mDatas.addAll(data)
44 | notifyDataSetChanged()
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/ktAdapter/src/main/java/tgs/adapter/BaseMultiAdapter.kt:
--------------------------------------------------------------------------------
1 | package tgs.adapter
2 |
3 | import android.databinding.DataBindingUtil
4 | import android.databinding.ViewDataBinding
5 | import android.support.annotation.LayoutRes
6 | import android.util.SparseIntArray
7 | import android.view.LayoutInflater
8 | import android.view.ViewGroup
9 | import kt.ktbindadapter.baseAdapter.BindViewHolder
10 |
11 | /**
12 | * 多type
13 | * 如果item内容填充较复杂,无法在item的xml中完成,需要在decorator完成填充,就使用这个
14 | * 或者需要子view的点击事件使用这个
15 | */
16 | abstract class BaseMultiAdapter : BaseAdapter, ViewDataBinding> {
17 | constructor(data: MutableList>) : super(data)
18 |
19 | private val layouts: SparseIntArray = SparseIntArray()
20 |
21 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindViewHolder {
22 | val binding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), layouts.get(viewType), parent, false)
23 | onCreateViewHolderDecorate(binding, viewType)
24 | return BindViewHolder(binding.root, binding)
25 | }
26 |
27 | open fun onCreateViewHolderDecorate(binding: ViewDataBinding, viewType: Int) {
28 |
29 | }
30 |
31 | override fun getItemViewType(position: Int): Int {
32 | return mDatas.get(position).itemType
33 | }
34 |
35 | fun addItemType(type: Int, @LayoutRes layoutResId: Int) {
36 | layouts.put(type, layoutResId)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
19 |
20 |
27 |
28 |
35 |
36 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/java/kt/ktbindadapter/Multi1Activity.kt:
--------------------------------------------------------------------------------
1 | package kt.ktbindadapter
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 | import android.support.v7.widget.DividerItemDecoration
6 | import android.view.View
7 | import kotlinx.android.synthetic.main.activity_sigle1.*
8 | import kt.ktbindadapter.bean.ItemInfo
9 | import tgs.adapter.MultiItem
10 | import tgs.adapter.SimpleMultiAdapter
11 | import tgs.kttool.util.ToastUtil
12 |
13 | class Multi1Activity : AppCompatActivity() {
14 | val itemInfos = mutableListOf>()
15 |
16 | companion object {
17 | val TYPE0 = 0
18 | val TYPE1 = 1
19 | }
20 |
21 | override fun onCreate(savedInstanceState: Bundle?) {
22 | super.onCreate(savedInstanceState)
23 | setContentView(R.layout.activity_multi1)
24 | initAdapter()
25 | loadData()
26 | }
27 |
28 | private fun initAdapter() {
29 | rv.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
30 | val multiAdapter = SimpleMultiAdapter(itemInfos)
31 | //添加布局
32 | multiAdapter.addItemType(TYPE0, R.layout.item_type0)
33 | multiAdapter.addItemType(TYPE1, R.layout.item_type1)
34 | //
35 | multiAdapter.setOnItemClickLisener { multiItem: MultiItem, view: View, i: Int ->
36 | ToastUtil.normal("点击的是item:" + multiItem + " 位置:" + i)
37 | }
38 | rv.setAdapter(multiAdapter)
39 | }
40 |
41 | private fun loadData() {
42 | for (i in 0..20) {
43 | if (i % 4 == 0) {
44 | itemInfos.add(MultiItem(TYPE0, ItemInfo("a", 1)))
45 | }
46 | itemInfos.add(MultiItem(TYPE1, ItemInfo("b", 1)))
47 | }
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/GlideCircleTransform.java:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapShader;
5 | import android.graphics.Canvas;
6 | import android.graphics.Paint;
7 |
8 | import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
9 | import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
10 |
11 | import java.security.MessageDigest;
12 |
13 | /**
14 | * 圆形
15 | */
16 | public class GlideCircleTransform extends BitmapTransformation {
17 |
18 | @Override
19 | protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
20 | return circleCrop(pool, toTransform);
21 | }
22 |
23 | private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
24 | if (source == null) return null;
25 |
26 | int size = Math.min(source.getWidth(), source.getHeight());
27 | int x = (source.getWidth() - size) / 2;
28 | int y = (source.getHeight() - size) / 2;
29 |
30 | Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
31 |
32 | Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
33 | if (result == null) {
34 | result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
35 | }
36 |
37 | Canvas canvas = new Canvas(result);
38 | Paint paint = new Paint();
39 | paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
40 | paint.setAntiAlias(true);
41 | float r = size / 2f;
42 | canvas.drawCircle(r, r, r, paint);
43 | return result;
44 | }
45 |
46 | @Override
47 | public void updateDiskCacheKey(MessageDigest messageDigest) {
48 |
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/ViewExt.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import android.view.LayoutInflater
4 | import android.view.View
5 | import android.view.ViewGroup
6 | import com.scwang.smartrefresh.layout.api.RefreshLayout
7 | import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
8 | import com.scwang.smartrefresh.layout.listener.OnRefreshListener
9 |
10 | fun ViewGroup.inflate(layoutRes: Int): View {
11 | return LayoutInflater.from(context).inflate(layoutRes, this, false)
12 | }
13 |
14 |
15 | /**
16 | * 双击间隔时间
17 | */
18 | const val INTERVAL = 400
19 |
20 | inline fun View.setDoubleClickLis(crossinline function: (View) -> Unit): View {
21 | var temTime: Long = 0
22 | this.setOnClickListener {
23 | if (System.currentTimeMillis() - temTime > INTERVAL) {
24 | temTime = System.currentTimeMillis()
25 | function(it)
26 | }
27 | }
28 | return this
29 | }
30 |
31 | inline fun doubleClickLis(crossinline function: (View) -> Unit): View.OnClickListener {
32 | var temTime: Long = 0
33 | return object : View.OnClickListener {
34 | override fun onClick(v: View) {
35 | if (System.currentTimeMillis() - temTime > INTERVAL) {
36 | temTime = System.currentTimeMillis()
37 | function(v)
38 | }
39 | }
40 | }
41 | }
42 |
43 |
44 | inline fun refreshListener(crossinline refreshLayout: (RefreshLayout) -> Unit): OnRefreshListener {
45 | return object : OnRefreshListener {
46 | override fun onRefresh(refreshLayout: RefreshLayout) {
47 | refreshLayout(refreshLayout)
48 | }
49 | }
50 | }
51 |
52 | inline fun loadMoreListener(crossinline refreshLayout: (RefreshLayout) -> Unit): OnLoadMoreListener {
53 | return object : OnLoadMoreListener {
54 | override fun onLoadMore(refreshLayout: RefreshLayout) {
55 | refreshLayout(refreshLayout)
56 | }
57 | }
58 | }
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/SPUtil.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import android.content.Context
4 | import tgs.kttool.ToolApplication.toolAppContext
5 | import kotlin.properties.ReadWriteProperty
6 | import kotlin.reflect.KProperty
7 |
8 |
9 | const val SPFileName = "Setting"
10 | /**
11 | * 使用defSP的话key为""在SPUtil中key会赋值成变量名
12 | * 所以一般用这个
13 | */
14 | inline fun R.defSP(default: T) = defSP("", default)
15 |
16 | /**
17 | * 指定key用这个
18 | */
19 | inline fun R.defSP(key: String, default: T) = SPUtil(key, default, R::class.java.name)
20 |
21 | class SPUtil(val key: String, val defValue: T, val fileName: String = SPFileName) : ReadWriteProperty {
22 | val sp by lazy {
23 | toolAppContext.getSharedPreferences(fileName, Context.MODE_PRIVATE)
24 | }
25 |
26 | override fun getValue(thisRef: Any?, property: KProperty<*>): T {
27 | val temKey = if (key.isEmpty()) property.name else key
28 | return when (defValue) {
29 | is String -> sp.getString(temKey, defValue)
30 | is Boolean -> sp.getBoolean(temKey, defValue)
31 | is Int -> sp.getInt(temKey, defValue)
32 | is Float -> sp.getFloat(temKey, defValue)
33 | is Long -> sp.getLong(temKey, defValue)
34 | else -> throw IllegalArgumentException("类型错误")
35 | } as T
36 | }
37 |
38 | override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
39 | val temKey = if (key.isEmpty()) property.name else key
40 | with(sp.edit()) {
41 | when (value) {
42 | is String -> putString(temKey, value)
43 | is Boolean -> putBoolean(temKey, value)
44 | is Int -> putInt(temKey, value)
45 | is Float -> putFloat(temKey, value)
46 | is Long -> putLong(temKey, value)
47 | else -> throw IllegalArgumentException("类型错误")
48 | }
49 | commit()
50 | }
51 | }
52 | }
53 |
54 | fun cleanSP(fileName: String = SPFileName) {
55 | toolAppContext.getSharedPreferences(fileName, Context.MODE_PRIVATE).edit().clear().commit()
56 | }
57 |
--------------------------------------------------------------------------------
/app/src/main/java/kt/ktbindadapter/Sigle2Activity.kt:
--------------------------------------------------------------------------------
1 | package kt.ktbindadapter
2 |
3 | import android.databinding.ObservableArrayList
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import android.support.v7.widget.DividerItemDecoration
7 | import android.view.View
8 | import kotlinx.android.synthetic.main.activity_sigle1.*
9 | import tgs.adapter.BaseSigleAdapter
10 | import kt.ktbindadapter.baseAdapter.BindViewHolder
11 | import kt.ktbindadapter.bean.ItemInfo
12 | import kt.ktbindadapter.databinding.ItemSigle2Binding
13 | import tgs.kttool.util.ToastUtil
14 |
15 | class Sigle2Activity : AppCompatActivity() {
16 | val listData = ObservableArrayList()
17 |
18 | init {
19 | for (i1 in 0..9) {
20 | listData.add(ItemInfo("name" + i1, i1))
21 | }
22 |
23 | }
24 |
25 | override fun onCreate(savedInstanceState: Bundle?) {
26 | super.onCreate(savedInstanceState)
27 | setContentView(R.layout.activity_sigle2)
28 | //单type,有item子view的点击事件
29 | val sigle2Adapger= object : BaseSigleAdapter(listData, R.layout.item_sigle2){
30 | override fun decorator(bean: ItemInfo, holder: BindViewHolder, position: Int) {
31 | holder.binding.run {
32 | tvName.setOnClickListener({ v -> childClickLisener!!.childClick(bean, tvName, position) })
33 | tvAge.setOnClickListener({ v -> childClickLisener!!.childClick(bean, tvAge, position) })
34 | }
35 | }
36 | }
37 | rv.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
38 | rv.setAdapter(sigle2Adapger)
39 |
40 | sigle2Adapger.setOnItemClickLisener { itemInfo, view, i ->
41 | ToastUtil.info("点击的是item" + itemInfo)
42 | }
43 | sigle2Adapger.setChildClickLisener { itemInfo: ItemInfo?, view: View, i: Int ->
44 | if (view.id == R.id.tv_name) {
45 | ToastUtil.success("点击的是子item中的tv_name")
46 | } else if (view.id == R.id.tv_age) {
47 | ToastUtil.success("点击的是子item中的tv_age")
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # KtBindAdapter
2 | 实现比较简单,主要运用了databinding的特性实现.
3 | 不建议使用,databinding并不那么美好。
4 | ### 使用方法
5 | ##### 添加依赖
6 | [](https://jitpack.io/#TianGuisen/KtBindAdapter)
7 | ```
8 | allprojects {
9 | repositories {
10 | ...
11 | maven { url 'https://jitpack.io' }
12 | }
13 | }
14 | ```
15 | ```
16 | dependencies {
17 | implementation 'com.github.TianGuisen:KtBindAdapter:1.1'
18 | }
19 | ```
20 | -------
21 | ##### item布局
22 | 所有item布局中name必须相同,推荐name="item"
23 | ```
24 |
25 |
28 |
31 |
32 | ```
33 | ##### 创建adapter
34 | ```
35 | //单type,直接创建SimpleAdapter即可,没有item子view的点击事件
36 | val testAdapter = SimpleAdapter(listData, R.layout.item_sigle1)
37 | //点击事件
38 | testAdapter.setOnItemClickLisener { itemInfo, view, i ->
39 |
40 | }
41 | ```
42 | ```
43 | //单type,没有item子view的点击事件,使用只需要创建SimpleAdapter
44 | val sigle2Adapger= object : BaseSigleAdapter(listData, R.layout.item_sigle2){
45 | override fun decorator(bean: ItemInfo, holder: BindViewHolder, position: Int) {
46 | holder.binding.run {
47 | tvName.setOnClickListener({ v -> childClickLisener!!.childClick(bean, tvName, position) })
48 | tvAge.setOnClickListener({ v -> childClickLisener!!.childClick(bean, tvAge, position) })
49 | }
50 | }
51 | }
52 | ```
53 | ```
54 | //多type布局,没有item子view的点击事件
55 | val multiAdapter = SimpleMultiAdapter(itemInfos)
56 | //添加布局
57 | multiAdapter.addItemType(TYPE0, R.layout.item_type0)
58 | multiAdapter.addItemType(TYPE1, R.layout.item_type1)
59 | ```
60 | ```
61 | ////多type布局,有item子view的点击事件
62 | val multiAdapter = object : BaseMultiAdapter(itemInfos) {
63 | override fun decorator(bean: MultiItem, holder: BindViewHolder, position: Int) {
64 | when (bean.itemType) {
65 | TYPE1 -> {
66 | (holder.binding as ItemType1Binding).run {
67 | tvName.setOnClickListener { v -> childClickLisener?.childClick(bean, tvName, position) }
68 | tvAge.setOnClickListener { v -> childClickLisener?.childClick(bean, tvAge, position) }
69 | }
70 | }
71 | }
72 | }
73 | }
74 | //添加布局
75 | multiAdapter.addItemType(TYPE0, R.layout.item_type0)
76 | multiAdapter.addItemType(TYPE1, R.layout.item_type1)
77 | ```
78 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/view/BaseBottomDia.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.view
2 |
3 | import android.graphics.Color
4 | import android.os.Bundle
5 | import android.support.design.widget.BottomSheetBehavior
6 | import android.support.design.widget.BottomSheetDialogFragment
7 | import android.support.design.widget.CoordinatorLayout
8 | import android.view.LayoutInflater
9 | import android.view.View
10 | import android.view.ViewGroup
11 | import kt.ktbindadapter.R
12 |
13 |
14 | class BaseBottomDia : BottomSheetDialogFragment() {
15 |
16 | private var height = 0
17 | fun getHeight() = height
18 | fun setHeight(height: Int): BaseBottomDia {
19 | this.height = height
20 | return this
21 | }
22 |
23 | private var mBottomSheetBehavior: BottomSheetBehavior? = null
24 | private val mBottomSheetBehaviorCallback = object : BottomSheetBehavior.BottomSheetCallback() {
25 |
26 | override fun onStateChanged(bottomSheet: View, newState: Int) {
27 | //禁止拖拽,
28 | if (newState == BottomSheetBehavior.STATE_DRAGGING) {
29 | //设置为收缩状态
30 | mBottomSheetBehavior!!.state = BottomSheetBehavior.STATE_COLLAPSED
31 | }
32 | }
33 |
34 | override fun onSlide(bottomSheet: View, slideOffset: Float) {}
35 | }
36 |
37 | /**
38 | * 如果没有调用setHight()方法去设置高度,那么必须要有id为content的布局用来测量高度,参考dia_base_bottom.xml
39 | */
40 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
41 | return inflater.inflate(R.layout.dia_base_bottom, null, false)
42 | }
43 |
44 | override fun onStart() {
45 | super.onStart()
46 | val view = view
47 | if (view != null) {
48 | view.post {
49 | val parent = view.parent as View
50 | val params = parent.layoutParams as CoordinatorLayout.LayoutParams
51 | val behavior = params.behavior
52 | mBottomSheetBehavior = behavior as BottomSheetBehavior
53 | mBottomSheetBehavior!!.setBottomSheetCallback(mBottomSheetBehaviorCallback)
54 | //设置高度
55 | if (height == 0) {
56 | val contentView = view.findViewById(R.id.content)
57 | mBottomSheetBehavior!!.peekHeight = contentView.height
58 | } else {
59 | mBottomSheetBehavior!!.peekHeight = height
60 | }
61 | parent.setBackgroundColor(Color.TRANSPARENT)
62 | }
63 | }
64 | }
65 |
66 |
67 | }
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/view/TDialog.kt:
--------------------------------------------------------------------------------
1 | package tg.my.core.view
2 |
3 | import android.os.Bundle
4 | import android.support.v4.app.DialogFragment
5 | import android.support.v4.app.FragmentManager
6 | import android.view.LayoutInflater
7 | import android.view.View
8 | import android.view.ViewGroup
9 | import android.widget.TextView
10 | import kt.ktbindadapter.R
11 | import tgs.kttool.util.setDoubleClickLis
12 |
13 |
14 | /**
15 | * dialog
16 | */
17 | class TDialog : DialogFragment() {
18 |
19 | private lateinit var tvTitle: TextView
20 | private lateinit var tvMsg: TextView
21 | private lateinit var tvOk: TextView
22 | private lateinit var tvCancel: TextView
23 |
24 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
25 | return View.inflate(context!!, R.layout.dia_t, null)
26 | }
27 |
28 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
29 | tvTitle = view.findViewById(R.id.tv_title)
30 | tvMsg = view.findViewById(R.id.tv_msg)
31 | tvOk = view.findViewById(R.id.tv_ok)
32 | tvCancel = view.findViewById(R.id.tv_cancel)
33 | }
34 |
35 | fun setOnOkClickLis(function: () -> Unit): TDialog {
36 | tvOk.setDoubleClickLis {
37 | function()
38 | }
39 | return this
40 | }
41 |
42 | fun setOnCancelClickLis(function: () -> Unit): TDialog {
43 | tvCancel.setDoubleClickLis {
44 | dismiss()
45 | function()
46 | }
47 | return this
48 | }
49 |
50 | fun title(title: String?): TDialog {
51 | if (title.isNullOrEmpty()) {
52 | tvTitle.visibility = View.GONE
53 | } else {
54 | tvTitle.text = title
55 | }
56 | return this
57 | }
58 |
59 | fun msg(msg: String): TDialog {
60 | tvMsg.text = msg
61 | return this
62 | }
63 |
64 | fun okText(okText: String): TDialog {
65 | tvOk.text = okText
66 | return this
67 | }
68 |
69 | fun cancelText(cancelText: String?): TDialog {
70 | if (cancelText.isNullOrEmpty()) {
71 | tvCancel.visibility = View.GONE
72 | } else {
73 | tvCancel.text = cancelText
74 | }
75 | return this
76 | }
77 |
78 | fun cancelable(b: Boolean): TDialog {
79 | setCancelable(b)
80 | return this
81 | }
82 |
83 | fun showNew(manager: FragmentManager?, tag: String?): TDialog {
84 | //必须调用这个showNow而不是普通的show,生命周期会同步执行
85 | super.showNow(manager, tag)
86 | return this
87 | }
88 |
89 |
90 | }
--------------------------------------------------------------------------------
/ktTool/src/main/res/layout/dia_t.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
13 |
14 |
19 |
20 |
27 |
28 |
40 |
41 |
46 |
47 |
53 |
54 |
63 |
64 |
68 |
69 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/app/src/main/java/kt/ktbindadapter/Multi2Activity.kt:
--------------------------------------------------------------------------------
1 | package kt.ktbindadapter
2 |
3 | import android.databinding.ViewDataBinding
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import android.support.v7.widget.DividerItemDecoration
7 | import android.view.View
8 | import kotlinx.android.synthetic.main.activity_sigle1.*
9 | import kt.ktbindadapter.baseAdapter.BindViewHolder
10 | import kt.ktbindadapter.bean.ItemInfo
11 | import kt.ktbindadapter.databinding.ItemType1Binding
12 | import tgs.adapter.BaseMultiAdapter
13 | import tgs.adapter.MultiItem
14 | import tgs.kttool.util.ToastUtil
15 |
16 | class Multi2Activity : AppCompatActivity() {
17 | val itemInfos = mutableListOf>()
18 |
19 | companion object {
20 | val TYPE0 = 0
21 | val TYPE1 = 1
22 | }
23 |
24 | override fun onCreate(savedInstanceState: Bundle?) {
25 | super.onCreate(savedInstanceState)
26 | setContentView(R.layout.activity_multi2)
27 | initAdapter()
28 | loadData()
29 | }
30 |
31 | private fun initAdapter() {
32 | rv.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
33 | val multiAdapter = object : BaseMultiAdapter(itemInfos) {
34 | override fun decorator(bean: MultiItem, holder: BindViewHolder, position: Int) {
35 | when (bean.itemType) {
36 | TYPE1 -> {
37 | (holder.binding as ItemType1Binding).run {
38 | tvName.setOnClickListener { v -> childClickLisener?.childClick(bean, tvName, position) }
39 | tvAge.setOnClickListener { v -> childClickLisener?.childClick(bean, tvAge, position) }
40 | }
41 | }
42 | }
43 | }
44 | }
45 | //添加布局
46 | multiAdapter.addItemType(TYPE0, R.layout.item_type0)
47 | multiAdapter.addItemType(TYPE1, R.layout.item_type1)
48 | //
49 | multiAdapter.setOnItemClickLisener { multiItem: MultiItem, view: View, i: Int ->
50 | ToastUtil.normal("点击的是item:" + multiItem + " 位置:" + i)
51 | }
52 | multiAdapter.setChildClickLisener { multiItem: MultiItem, view: View, i: Int ->
53 | if (view.id == R.id.tv_name) {
54 | ToastUtil.normal("点击的是tv_name " + multiItem.data.name)
55 | } else if (view.id == R.id.tv_age) {
56 | ToastUtil.normal("点击的是tv_age " + multiItem.data.age)
57 | }
58 | }
59 | rv.setAdapter(multiAdapter)
60 | }
61 |
62 | private fun loadData() {
63 | for (i in 0..20) {
64 | if (i % 4 == 0) {
65 | itemInfos.add(MultiItem(TYPE0, ItemInfo("a", 1)))
66 | }
67 | itemInfos.add(MultiItem(TYPE1, ItemInfo("b", 1)))
68 | }
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/ViewBindingAdapter.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import android.databinding.BindingAdapter
4 | import android.databinding.InverseBindingAdapter
5 | import android.databinding.InverseBindingListener
6 | import android.view.View
7 | import android.widget.ImageView
8 | import com.bumptech.glide.Glide
9 | import tgs.kttool.view.BindEditText
10 |
11 |
12 | /**
13 | * 可见控制
14 | */
15 | @BindingAdapter("setVisible")
16 | fun setVisible(view: View, visible: Boolean) {
17 | if (visible) {
18 | view.visibility = View.VISIBLE
19 | } else {
20 | view.visibility = View.GONE
21 | }
22 | }
23 |
24 | @BindingAdapter("focusAttrChanged")
25 | fun setChangeListener(aView: BindEditText, focusAttrChange: InverseBindingListener) {
26 | aView.setListener(object : BindEditText.OnFocusChangedListener {
27 | override fun onChanged() {
28 | focusAttrChange.onChange()
29 | }
30 | })
31 | }
32 |
33 | @InverseBindingAdapter(attribute = "focus", event = "focusAttrChanged")
34 | fun isFocus(view: BindEditText): Boolean {
35 | return view.hasFocus()
36 | }
37 |
38 | /**
39 | * 焦点控制和监听
40 | * 传入Boolean就是控制
41 | * 传入ObservableBoolean是控制和监听
42 | */
43 | @BindingAdapter("focus")
44 | fun setFocus(view: BindEditText, focus: Boolean) {
45 | if (focus) {
46 | view.isFocusableInTouchMode = true
47 | view.requestFocus()
48 | } else {
49 | view.clearFocus()
50 | }
51 | }
52 |
53 | /**
54 | * glide加载网络图片
55 | */
56 | @BindingAdapter("imageUrl")
57 | fun imageUri(imageView: ImageView, imageUrl: String) {
58 | Glide.with(imageView.context).load(imageUrl).into(imageView)
59 | }
60 |
61 | /**
62 | * glide加载本地图片
63 | */
64 | @BindingAdapter("imageUrl")
65 | fun imageUrl(imageView: ImageView, res: Int) {
66 | Glide.with(imageView.context).load(res).into(imageView)
67 | }
68 |
69 | ///**
70 | // * 焦点改变监听
71 | // */
72 | //@BindingAdapter("focusChange")
73 | //fun onFocusChangeReply(view: View, onFocusChangeReply: Consumer) {
74 | // view.onFocusChangeListener = View.OnFocusChangeListener { mV, hasFocus ->
75 | // onFocusChangeReply.accept(hasFocus)
76 | // }
77 | //}
78 | //
79 | ///**
80 | // * onTouch监听
81 | // */
82 | //@BindingAdapter("touch")
83 | //fun onTouchReply(view: View, onTouchReply: Function) {
84 | // view.setOnTouchListener { mV, event ->
85 | // onTouchReply.apply(event)
86 | // }
87 | //}
88 | //
89 | ///**
90 | // * 刷新控件,可以换成任意其他的
91 | // */
92 | //@BindingAdapter("load")
93 | //fun onLoadReply(smartRefreshLayout: SmartRefreshLayout, onRefreshReply: Consumer) {
94 | // smartRefreshLayout.setOnRefreshListener {
95 | // onRefreshReply.accept(0)
96 | // }
97 | // smartRefreshLayout.setOnLoadMoreListener {
98 | // onRefreshReply.accept(1)
99 | // }
100 | //}
101 |
102 |
103 | //@BindingAdapter("checkedChange")
104 | //fun onRadioGroupCheckedChangeReply(radioGroup: RadioGroup, onCheckedReply: Consumer) {
105 | // radioGroup.setOnCheckedChangeListener { group, checkedId -> onCheckedReply.accept(checkedId) }
106 | //}
--------------------------------------------------------------------------------
/ktAdapter/src/main/java/tgs/adapter/BaseAdapter.kt:
--------------------------------------------------------------------------------
1 | package tgs.adapter
2 |
3 | import android.databinding.ViewDataBinding
4 | import android.support.v7.widget.RecyclerView
5 | import android.view.View
6 | import kt.ktbindadapter.baseAdapter.BindViewHolder
7 |
8 | abstract class BaseAdapter internal constructor(datas: MutableList) : RecyclerView.Adapter>() {
9 | var mDatas: MutableList = datas
10 | var itemClickLisener: OnItemClickLisener? = null
11 | var childClickLisener: OnChildClickLisener? = null
12 | var itemLongClickLisener: OnItemLongClickLisener? = null
13 |
14 |
15 | fun setChildClickLisener(function: (E, View, Int) -> Unit) {
16 | this.childClickLisener = object : OnChildClickLisener {
17 | override fun childClick(bean: E, view: View, position: Int) {
18 | function(bean, view, position)
19 | }
20 | }
21 | }
22 |
23 | fun setOnItemClickLisener(itemClickLisener: OnItemClickLisener) {
24 | this.itemClickLisener = itemClickLisener
25 | }
26 |
27 | fun setOnItemClickLisener(function: (E, View, Int) -> Unit) {
28 | this.itemClickLisener = object : OnItemClickLisener {
29 | override fun itemClick(bean: E, view: View, position: Int) {
30 | function(bean, view, position)
31 | }
32 | }
33 | }
34 |
35 | fun setItemLongClickLisener(function: (E, View, Int) -> Unit) {
36 | this.itemLongClickLisener = object : OnItemLongClickLisener {
37 | override fun itemLongClick(bean: E, view: View, position: Int) {
38 | function(bean, view, position)
39 | }
40 | }
41 | }
42 |
43 | interface OnItemClickLisener {
44 | fun itemClick(bean: E, view: View, position: Int)
45 | }
46 |
47 | interface OnChildClickLisener {
48 | fun childClick(bean: E, view: View, position: Int)
49 | }
50 |
51 | interface OnItemLongClickLisener {
52 | fun itemLongClick(bean: E, view: View, position: Int)
53 | }
54 |
55 | override fun onBindViewHolder(holder: BindViewHolder, position: Int) {
56 | val bean = mDatas[position]
57 | val itemView = holder.binding.getRoot()
58 | if (itemClickLisener != null) {
59 | itemView.setOnClickListener {
60 | itemClickLisener!!.itemClick(bean, holder.binding.getRoot(), position)
61 | }
62 | }
63 | decorator(bean, holder, position)
64 | //如果是BaseMultiAdapter需要处理一下
65 | if (mDatas[position] is MultiItem<*>) {
66 | val pinnedHeaderEntity = mDatas[position] as MultiItem<*>
67 | // 在module中BR.item运行时会报错,但是在app中不会
68 | // 如果只用一种name,比如item,那么BR.item永远是1
69 | holder.binding.setVariable(1, pinnedHeaderEntity.data)
70 | } else {
71 | holder.binding.setVariable(1, mDatas[position])
72 | }
73 | holder.binding.executePendingBindings()
74 | }
75 |
76 | abstract fun decorator(bean: E, holder: BindViewHolder, position: Int)
77 |
78 | open fun remove(position: Int) {
79 | mDatas.removeAt(position)
80 | notifyItemRemoved(position)
81 | }
82 |
83 | open fun clear() {
84 | mDatas.clear()
85 | notifyDataSetChanged()
86 | }
87 |
88 | override fun getItemCount(): Int {
89 | return mDatas.size
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
11 |
16 |
21 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
172 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/view/RotateLoading.java:
--------------------------------------------------------------------------------
1 | package tgs.kttool.view;
2 |
3 | import android.animation.Animator;
4 | import android.animation.AnimatorSet;
5 | import android.animation.ObjectAnimator;
6 | import android.content.Context;
7 | import android.graphics.Canvas;
8 | import android.graphics.Color;
9 | import android.graphics.Paint;
10 | import android.graphics.RectF;
11 | import android.util.AttributeSet;
12 | import android.view.MotionEvent;
13 | import android.view.View;
14 | import android.view.animation.LinearInterpolator;
15 |
16 | import static tgs.kttool.ToolApplication.toolAppContext;
17 |
18 |
19 | /**
20 | * Created by Administrator on 2017/3/20.
21 | */
22 |
23 | public class RotateLoading extends View {
24 |
25 | /**
26 | * 圆的粗细
27 | */
28 | private int width = dp2px(3);
29 | /**
30 | * 半径
31 | */
32 | private int radius = dp2px(30);
33 | /**
34 | * 阴影偏移
35 | */
36 | private int shadowOffset = dp2px(3);
37 | /**
38 | * 圆的颜色
39 | */
40 | private int color = Color.parseColor("#FB7299");
41 |
42 | private static final int DEFAULT_SPEED_OF_DEGREE = 10;
43 |
44 | private Paint mPaint;
45 |
46 | private RectF loadingRectF;
47 | private RectF shadowRectF;
48 |
49 | private int topDegree = 10;
50 | private int bottomDegree = 190;
51 |
52 | private float arc;
53 | private boolean changeBigger = true;
54 |
55 |
56 | private boolean isStart = false;
57 |
58 | private int speedOfDegree;
59 |
60 | private float speedOfArc;
61 |
62 | public RotateLoading(Context context) {
63 | super(context);
64 | initView(context, null);
65 | }
66 |
67 | public RotateLoading(Context context, AttributeSet attrs) {
68 | super(context, attrs);
69 | initView(context, attrs);
70 | }
71 |
72 | public RotateLoading(Context context, AttributeSet attrs, int defStyleAttr) {
73 | super(context, attrs, defStyleAttr);
74 | initView(context, attrs);
75 | }
76 |
77 | private void initView(Context context, AttributeSet attrs) {
78 | speedOfDegree = DEFAULT_SPEED_OF_DEGREE;
79 |
80 | speedOfDegree = 10;
81 | speedOfArc = speedOfDegree / 4;
82 | mPaint = new Paint();
83 | mPaint.setColor(color);
84 | mPaint.setAntiAlias(true);
85 | mPaint.setStyle(Paint.Style.STROKE);
86 | mPaint.setStrokeWidth(width);
87 | mPaint.setStrokeCap(Paint.Cap.ROUND);
88 | }
89 |
90 | @Override
91 | protected void onSizeChanged(int w, int h, int oldw, int oldh) {
92 | super.onSizeChanged(w, h, oldw, oldh);
93 | int width = getWidth();
94 | int height = getHeight();
95 | arc = 10;
96 | loadingRectF = new RectF(width / 2 - radius, height / 2 - radius, width / 2 + radius, height / 2 + radius);
97 | shadowRectF = new RectF(width / 2 - radius, height / 2 - radius + shadowOffset, width / 2 + radius, height / 2 + radius + shadowOffset);
98 | }
99 |
100 |
101 | @Override
102 | protected void onDraw(Canvas canvas) {
103 | super.onDraw(canvas);
104 |
105 | if (!isStart) {
106 | return;
107 | }
108 |
109 | mPaint.setColor(Color.parseColor("#1a000000"));
110 | canvas.drawArc(shadowRectF, topDegree, arc, false, mPaint);
111 | canvas.drawArc(shadowRectF, bottomDegree, arc, false, mPaint);
112 |
113 | mPaint.setColor(color);
114 | canvas.drawArc(loadingRectF, topDegree, arc, false, mPaint);
115 | canvas.drawArc(loadingRectF, bottomDegree, arc, false, mPaint);
116 |
117 | topDegree += speedOfDegree;
118 | bottomDegree += speedOfDegree;
119 | if (topDegree > 360) {
120 | topDegree = topDegree - 360;
121 | }
122 | if (bottomDegree > 360) {
123 | bottomDegree = bottomDegree - 360;
124 | }
125 |
126 | if (changeBigger) {
127 | if (arc < 160) {
128 | arc += speedOfArc;
129 | invalidate();
130 | }
131 | } else {
132 | if (arc > speedOfDegree) {
133 | arc -= 2 * speedOfArc;
134 | invalidate();
135 | }
136 | }
137 | if (arc >= 160 || arc <= 10) {
138 | changeBigger = !changeBigger;
139 | invalidate();
140 | }
141 | }
142 |
143 | public void setLoadingColor(int color) {
144 | this.color = color;
145 | }
146 |
147 | public int getLoadingColor() {
148 | return color;
149 | }
150 |
151 | public void start() {
152 | startAnimator();
153 | isStart = true;
154 | invalidate();
155 | }
156 |
157 | public void stop() {
158 | stopAnimator();
159 | invalidate();
160 | }
161 |
162 | public boolean isStart() {
163 | return isStart;
164 | }
165 |
166 | private void startAnimator() {
167 | ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(this, "scaleX", 0.0f, 1);
168 | ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(this, "scaleY", 0.0f, 1);
169 | scaleXAnimator.setDuration(300);
170 | scaleXAnimator.setInterpolator(new LinearInterpolator());
171 | scaleYAnimator.setDuration(300);
172 | scaleYAnimator.setInterpolator(new LinearInterpolator());
173 | AnimatorSet animatorSet = new AnimatorSet();
174 | animatorSet.playTogether(scaleXAnimator, scaleYAnimator);
175 | animatorSet.start();
176 | }
177 |
178 | private void stopAnimator() {
179 | ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(this, "scaleX", 1, 0);
180 | ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(this, "scaleY", 1, 0);
181 | scaleXAnimator.setDuration(300);
182 | scaleXAnimator.setInterpolator(new LinearInterpolator());
183 | scaleYAnimator.setDuration(300);
184 | scaleYAnimator.setInterpolator(new LinearInterpolator());
185 | AnimatorSet animatorSet = new AnimatorSet();
186 | animatorSet.playTogether(scaleXAnimator, scaleYAnimator);
187 | animatorSet.addListener(new Animator.AnimatorListener() {
188 | @Override
189 | public void onAnimationStart(Animator animation) {
190 |
191 | }
192 |
193 | @Override
194 | public void onAnimationEnd(Animator animation) {
195 | isStart = false;
196 | }
197 |
198 | @Override
199 | public void onAnimationCancel(Animator animation) {
200 |
201 | }
202 |
203 | @Override
204 | public void onAnimationRepeat(Animator animation) {
205 |
206 | }
207 | });
208 | animatorSet.start();
209 | }
210 |
211 | @Override
212 | public boolean onTouchEvent(MotionEvent event) {
213 | return isStart;
214 | }
215 |
216 | public int dp2px(int dp) {
217 | float density = toolAppContext.getResources().getDisplayMetrics().density;
218 | return (int) (density * dp + 0.5);
219 | }
220 | }
221 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/DateUtil.kt:
--------------------------------------------------------------------------------
1 | package tg.my.util
2 |
3 | import java.text.ParseException
4 | import java.text.SimpleDateFormat
5 | import java.util.*
6 |
7 | /**
8 | * 日期工具类
9 | *
10 | * 主要实现了日期的常用操作
11 | */
12 | object DateUtil {
13 |
14 | /**
15 | * yyyy-MM-dd HH:mm:ss字符串
16 | */
17 | val DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"
18 |
19 | /**
20 | * yyyy-MM-dd字符串
21 | */
22 | val DEFAULT_FORMAT_DATE = "yyyy-MM-dd"
23 |
24 | /**
25 | * HH:mm:ss字符串
26 | */
27 | val DEFAULT_FORMAT_TIME = "HH:mm:ss"
28 |
29 | /**
30 | * yyyy-MM-dd HH:mm:ss格式
31 | */
32 | val defaultDateTimeFormat: ThreadLocal = object : ThreadLocal() {
33 |
34 | override fun initialValue(): SimpleDateFormat {
35 | return SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT)
36 | }
37 |
38 | }
39 |
40 | /**
41 | * yyyy-MM-dd格式
42 | */
43 | val defaultDateFormat: ThreadLocal = object : ThreadLocal() {
44 |
45 | override fun initialValue(): SimpleDateFormat {
46 | return SimpleDateFormat(DEFAULT_FORMAT_DATE)
47 | }
48 |
49 | }
50 |
51 | /**
52 | * HH:mm:ss格式
53 | */
54 | val defaultTimeFormat: ThreadLocal = object : ThreadLocal() {
55 |
56 | override fun initialValue(): SimpleDateFormat {
57 | return SimpleDateFormat(DEFAULT_FORMAT_TIME)
58 | }
59 |
60 | }
61 |
62 | /**
63 | * 将long时间转成yyyy-MM-dd HH:mm:ss字符串
64 | *
65 | * @param timeInMillis 时间long值
66 | * @return yyyy-MM-dd HH:mm:ss
67 | */
68 | fun getDateTimeFromMillis(timeInMillis: Long): String {
69 | return getDateTimeFormat(Date(timeInMillis))
70 | }
71 |
72 | /**
73 | * 将long时间转成yyyy-MM-dd字符串
74 | *
75 | * @param timeInMillis
76 | * @return yyyy-MM-dd
77 | */
78 | fun getDateFromMillis(timeInMillis: Long): String {
79 | return getDateFormat(Date(timeInMillis))
80 | }
81 |
82 | /**
83 | * 将date转成yyyy-MM-dd HH:mm:ss字符串
84 | *
85 | *
86 | * @param date Date对象
87 | * @return yyyy-MM-dd HH:mm:ss
88 | */
89 | fun getDateTimeFormat(date: Date): String {
90 | return dateSimpleFormat(date, defaultDateTimeFormat.get())
91 | }
92 |
93 | /**
94 | * 将年月日的int转成yyyy-MM-dd的字符串
95 | *
96 | * @param year 年
97 | * @param month 月 1-12
98 | * @param day 日
99 | * 注:月表示Calendar的月,比实际小1
100 | * 对输入项未做判断
101 | */
102 | fun getDateFormat(year: Int, month: Int, day: Int): String {
103 | return getDateFormat(getDate(year, month, day))
104 | }
105 |
106 | /**
107 | * 将date转成yyyy-MM-dd字符串
108 | *
109 | * @param date Date对象
110 | * @return yyyy-MM-dd
111 | */
112 | fun getDateFormat(date: Date): String {
113 | return dateSimpleFormat(date, defaultDateFormat.get())
114 | }
115 |
116 | /**
117 | * 获得HH:mm:ss的时间
118 | *
119 | * @param date
120 | * @return
121 | */
122 | fun getTimeFormat(date: Date): String {
123 | return dateSimpleFormat(date, defaultTimeFormat.get())
124 | }
125 |
126 | /**
127 | * 格式化日期显示格式
128 | *
129 | * @param sdate 原始日期格式 "yyyy-MM-dd"
130 | * @param format 格式化后日期格式
131 | * @return 格式化后的日期显示
132 | */
133 | fun dateFormat(sdate: String, format: String): String {
134 | val formatter = SimpleDateFormat(format)
135 | val date = java.sql.Date.valueOf(sdate)
136 | return dateSimpleFormat(date, formatter)
137 | }
138 |
139 | /**
140 | * 格式化日期显示格式
141 | *
142 | * @param date Date对象
143 | * @param format 格式化后日期格式
144 | * @return 格式化后的日期显示
145 | */
146 | fun dateFormat(date: Date, format: String): String {
147 | val formatter = SimpleDateFormat(format)
148 | return dateSimpleFormat(date, formatter)
149 | }
150 |
151 | /**
152 | * 将date转成字符串
153 | *
154 | * @param date Date
155 | * @param format SimpleDateFormat
156 | *
157 | * 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式
158 | * @return yyyy-MM-dd HH:mm:ss
159 | */
160 | fun dateSimpleFormat(date: Date?, format: SimpleDateFormat?): String {
161 | var format = format
162 | if (format == null)
163 | format = defaultDateTimeFormat.get()
164 | return if (date == null) "" else format!!.format(date)
165 | }
166 |
167 | /**
168 | * 将"yyyy-MM-dd HH:mm:ss" 格式的字符串转成Date
169 | *
170 | * @param strDate 时间字符串
171 | * @return Date
172 | */
173 | fun getDateByDateTimeFormat(strDate: String): Date? {
174 | return getDateByFormat(strDate, defaultDateTimeFormat.get())
175 | }
176 |
177 | /**
178 | * 将"yyyy-MM-dd" 格式的字符串转成Date
179 | *
180 | * @param strDate
181 | * @return Date
182 | */
183 | fun getDateByDateFormat(strDate: String): Date? {
184 | return getDateByFormat(strDate, defaultDateFormat.get())
185 | }
186 |
187 | /**
188 | * 将指定格式的时间字符串转成Date对象
189 | *
190 | * @param strDate 时间字符串
191 | * @param format 格式化字符串
192 | * @return Date
193 | */
194 | fun getDateByFormat(strDate: String, format: String): Date? {
195 | return getDateByFormat(strDate, SimpleDateFormat(format))
196 | }
197 |
198 | /**
199 | * 将String字符串按照一定格式转成Date
200 | * 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式
201 | *
202 | * @param strDate 时间字符串
203 | * @param format SimpleDateFormat对象
204 | * @throws ParseException 日期格式转换出错
205 | */
206 | private fun getDateByFormat(strDate: String, format: SimpleDateFormat?): Date? {
207 | var format = format
208 | if (format == null)
209 | format = defaultDateTimeFormat.get()
210 | try {
211 | return format!!.parse(strDate)
212 | } catch (e: ParseException) {
213 | e.printStackTrace()
214 | }
215 |
216 | return null
217 | }
218 |
219 | /**
220 | * 将年月日的int转成date
221 | *
222 | * @param year 年
223 | * @param month 月 1-12
224 | * @param day 日
225 | * 注:月表示Calendar的月,比实际小1
226 | */
227 | fun getDate(year: Int, month: Int, day: Int): Date {
228 | val mCalendar = Calendar.getInstance()
229 | mCalendar.set(year, month - 1, day)
230 | return mCalendar.time
231 | }
232 |
233 | /**
234 | * 求两个日期相差天数
235 | *
236 | * @param strat 起始日期,格式yyyy-MM-dd
237 | * @param end 终止日期,格式yyyy-MM-dd
238 | * @return 两个日期相差天数
239 | */
240 | fun getIntervalDays(strat: String, end: String): Long {
241 | return (java.sql.Date.valueOf(end).time - java.sql.Date
242 | .valueOf(strat).time) / (3600 * 24 * 1000)
243 | }
244 |
245 | /**
246 | * 获得当前年份
247 | *
248 | * @return year(int)
249 | */
250 | val currentYear: Int
251 | get() {
252 | val mCalendar = Calendar.getInstance()
253 | return mCalendar.get(Calendar.YEAR)
254 | }
255 |
256 | /**
257 | * 获得当前月份
258 | *
259 | * @return month(int) 1-12
260 | */
261 | val currentMonth: Int
262 | get() {
263 | val mCalendar = Calendar.getInstance()
264 | return mCalendar.get(Calendar.MONTH) + 1
265 | }
266 |
267 | /**
268 | * 获得当月几号
269 | *
270 | * @return day(int)
271 | */
272 | val dayOfMonth: Int
273 | get() {
274 | val mCalendar = Calendar.getInstance()
275 | return mCalendar.get(Calendar.DAY_OF_MONTH)
276 | }
277 |
278 | /**
279 | * 获得今天的日期(格式:yyyy-MM-dd)
280 | *
281 | * @return yyyy-MM-dd
282 | */
283 | val today: String
284 | get() {
285 | val mCalendar = Calendar.getInstance()
286 | return getDateFormat(mCalendar.time)
287 | }
288 |
289 | /**
290 | * 获得年月日数据
291 | *
292 | * @param sDate yyyy-MM-dd格式
293 | * @return arr[0]:年, arr[1]:月 0-11 , arr[2]日
294 | */
295 | fun getYearMonthAndDayFrom(sDate: String): IntArray {
296 | return getYearMonthAndDayFromDate(getDateByDateFormat(sDate))
297 | }
298 |
299 | /**
300 | * 获得年月日数据
301 | *
302 | * @return arr[0]:年, arr[1]:月 0-11 , arr[2]日
303 | */
304 | fun getYearMonthAndDayFromDate(date: Date?): IntArray {
305 | val calendar = Calendar.getInstance()
306 | calendar.time = date!!
307 | val arr = IntArray(3)
308 | arr[0] = calendar.get(Calendar.YEAR)
309 | arr[1] = calendar.get(Calendar.MONTH)
310 | arr[2] = calendar.get(Calendar.DAY_OF_MONTH)
311 | return arr
312 | }
313 | }
314 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/FileUtil.kt:
--------------------------------------------------------------------------------
1 | package tg.my.util
2 |
3 |
4 | import android.os.Environment
5 | import android.text.TextUtils
6 | import java.io.File
7 | import java.io.FilenameFilter
8 | import java.io.IOException
9 | import java.util.*
10 |
11 |
12 | object FileUtil {
13 | /**
14 | * 分隔符.
15 | */
16 | val FILE_EXTENSION_SEPARATOR = "."
17 |
18 | /**
19 | * "/"
20 | */
21 | val SEP = File.separator
22 |
23 | /**
24 | * SD卡根目录
25 | */
26 | val SDPATH = Environment.getExternalStorageDirectory().toString() + File.separator
27 |
28 | /**
29 | * 判断SD卡是否可用
30 | *
31 | * @return SD卡可用返回true
32 | */
33 | fun hasSdcard(): Boolean {
34 | val status = Environment.getExternalStorageState()
35 | return Environment.MEDIA_MOUNTED == status
36 | }
37 |
38 |
39 | /**
40 | * 获取某个目录下的文件名
41 | *
42 | * @param dirPath 目录
43 | * @param fileFilter 过滤器
44 | * @return 某个目录下的所有文件名
45 | */
46 | fun getFileNameList(dirPath: String,
47 | fileFilter: FilenameFilter?): List {
48 | if (fileFilter == null)
49 | return getFileNameList(dirPath)
50 | if (TextUtils.isEmpty(dirPath))
51 | return emptyList()
52 | val dir = File(dirPath)
53 |
54 | val files = dir.listFiles(fileFilter) ?: return emptyList()
55 |
56 | val conList = ArrayList()
57 | for (file in files) {
58 | if (file.isFile)
59 | conList.add(file.name)
60 | }
61 | return conList
62 | }
63 |
64 | /**
65 | * 获取某个目录下的文件名
66 | *
67 | * @param dirPath 目录
68 | * @return 某个目录下的所有文件名
69 | */
70 | fun getFileNameList(dirPath: String): List {
71 | if (TextUtils.isEmpty(dirPath))
72 | return emptyList()
73 | val dir = File(dirPath)
74 | val files = dir.listFiles() ?: return emptyList()
75 | val conList = ArrayList()
76 | for (file in files) {
77 | if (file.isFile)
78 | conList.add(file.name)
79 | }
80 | return conList
81 | }
82 |
83 | /**
84 | * 获取某个目录下的指定扩展名的文件名称
85 | *
86 | * @param dirPath 目录
87 | * @return 某个目录下的所有文件名
88 | */
89 | fun getFileNameList(dirPath: String,
90 | extension: String): List {
91 | if (TextUtils.isEmpty(dirPath))
92 | return emptyList()
93 | val dir = File(dirPath)
94 | val files = dir.listFiles { dir, filename -> if (filename.indexOf(".$extension") > 0) true else false }
95 | ?: return emptyList()
96 | val conList = ArrayList()
97 | for (file in files) {
98 | if (file.isFile)
99 | conList.add(file.name)
100 | }
101 | return conList
102 | }
103 |
104 | /**
105 | * 获得文件的扩展名
106 | *
107 | * @param filePath 文件路径
108 | * @return 如果没有扩展名,返回""
109 | */
110 | fun getFileExtension(filePath: String): String? {
111 | if (TextUtils.isEmpty(filePath)) {
112 | return filePath
113 | }
114 | val extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR)
115 | val filePosi = filePath.lastIndexOf(File.separator)
116 | if (extenPosi == -1) {
117 | return ""
118 | }
119 | return if (filePosi >= extenPosi) "" else filePath.substring(extenPosi + 1)
120 | }
121 |
122 | /**
123 | * 创建文件
124 | *
125 | * @param path 文件的绝对路径
126 | * @return
127 | */
128 | fun createFile(path: String): Boolean {
129 | return if (TextUtils.isEmpty(path)) false else createFile(File(path))
130 | }
131 |
132 | /**
133 | * 创建文件
134 | *
135 | * @param file
136 | * @return 创建成功返回true
137 | */
138 | fun createFile(file: File?): Boolean {
139 | if (file == null || !makeDirs(getFolderName(file.absolutePath)))
140 | return false
141 | if (!file.exists())
142 | try {
143 | return file.createNewFile()
144 | } catch (e: IOException) {
145 | e.printStackTrace()
146 | return false
147 | }
148 |
149 | return false
150 | }
151 |
152 | /**
153 | * 创建目录(可以是多个)
154 | *
155 | * @param filePath 目录路径
156 | * @return 如果路径为空时,返回false;如果目录创建成功,则返回true,否则返回false
157 | */
158 | fun makeDirs(filePath: String?): Boolean {
159 | if (TextUtils.isEmpty(filePath)) {
160 | return false
161 | }
162 | val folder = File(filePath!!)
163 | return if (folder.exists() && folder.isDirectory)
164 | true
165 | else
166 | folder
167 | .mkdirs()
168 | }
169 |
170 | /**
171 | * 创建目录(可以是多个)
172 | *
173 | * @param dir 目录
174 | * @return 如果目录创建成功,则返回true,否则返回false
175 | */
176 | fun makeDirs(dir: File?): Boolean {
177 | if (dir == null)
178 | return false
179 | return if (dir.exists() && dir.isDirectory) true else dir.mkdirs()
180 | }
181 |
182 | /**
183 | * 判断文件是否存在
184 | *
185 | * @param filePath 文件路径
186 | * @return 如果路径为空或者为空白字符串,就返回false;如果文件存在,且是文件,
187 | * 就返回true;如果不是文件或者不存在,则返回false
188 | */
189 | fun isFileExist(filePath: String): Boolean {
190 | if (TextUtils.isEmpty(filePath)) {
191 | return false
192 | }
193 | val file = File(filePath)
194 | return file.exists() && file.isFile
195 | }
196 |
197 | /**
198 | * 获得不带扩展名的文件名称
199 | *
200 | * @param filePath 文件路径
201 | * @return
202 | */
203 | fun getFileNameWithoutExtension(filePath: String): String? {
204 | if (TextUtils.isEmpty(filePath)) {
205 | return filePath
206 | }
207 | val extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR)
208 | val filePosi = filePath.lastIndexOf(File.separator)
209 | if (filePosi == -1) {
210 | return if (extenPosi == -1)
211 | filePath
212 | else
213 | filePath.substring(0,
214 | extenPosi)
215 | }
216 | if (extenPosi == -1) {
217 | return filePath.substring(filePosi + 1)
218 | }
219 | return if (filePosi < extenPosi)
220 | filePath.substring(filePosi + 1,
221 | extenPosi)
222 | else
223 | filePath.substring(filePosi + 1)
224 | }
225 |
226 | /**
227 | * 获得文件名
228 | *
229 | * @param filePath 文件路径
230 | * @return 如果路径为空或空串,返回路径名;不为空时,返回文件名
231 | */
232 | fun getFileName(filePath: String): String? {
233 | if (TextUtils.isEmpty(filePath)) {
234 | return filePath
235 | }
236 | val filePosi = filePath.lastIndexOf(File.separator)
237 | return if (filePosi == -1) filePath else filePath.substring(filePosi + 1)
238 | }
239 |
240 | /**
241 | * 获得所在目录名称
242 | *
243 | * @param filePath 文件的绝对路径
244 | * @return 如果路径为空或空串,返回路径名;不为空时,如果为根目录,返回"";
245 | * 如果不是根目录,返回所在目录名称,格式如:C:/Windows/Boot
246 | */
247 | fun getFolderName(filePath: String): String? {
248 | if (TextUtils.isEmpty(filePath)) {
249 | return filePath
250 | }
251 | val filePosi = filePath.lastIndexOf(File.separator)
252 | return if (filePosi == -1) "" else filePath.substring(0, filePosi)
253 | }
254 |
255 | /**
256 | * 判断目录是否存在
257 | *
258 | * @param
259 | * @return 如果路径为空或空白字符串,返回false;如果目录存在且,确实是目录文件夹,
260 | * 返回true;如果不是文件夹或者不存在,则返回false
261 | */
262 | fun isFolderExist(directoryPath: String): Boolean {
263 | if (TextUtils.isEmpty(directoryPath)) {
264 | return false
265 | }
266 | val dire = File(directoryPath)
267 | return dire.exists() && dire.isDirectory
268 | }
269 |
270 | /**
271 | * 删除指定文件或指定目录内的所有文件
272 | *
273 | * @param path 文件或目录的绝对路径
274 | * @return 路径为空或空白字符串,返回true;文件不存在,返回true;文件删除返回true;
275 | * 文件删除异常返回false
276 | */
277 | fun deleteFile(path: String): Boolean {
278 | return if (TextUtils.isEmpty(path)) {
279 | true
280 | } else deleteFile(File(path))
281 | }
282 |
283 | /**
284 | * 删除指定文件或指定目录内的所有文件
285 | *
286 | * @param file
287 | * @return 路径为空或空白字符串,返回true;文件不存在,返回true;文件删除返回true;
288 | * 文件删除异常返回false
289 | */
290 | fun deleteFile(file: File?): Boolean {
291 | if (file == null)
292 | throw NullPointerException("file is null")
293 | if (!file.exists()) {
294 | return true
295 | }
296 | if (file.isFile) {
297 | return file.delete()
298 | }
299 | if (!file.isDirectory) {
300 | return false
301 | }
302 |
303 | val files = file.listFiles() ?: return true
304 | for (f in files) {
305 | if (f.isFile) {
306 | f.delete()
307 | } else if (f.isDirectory) {
308 | deleteFile(f.absolutePath)
309 | }
310 | }
311 | return file.delete()
312 | }
313 |
314 | /**
315 | * 删除指定目录中特定的文件
316 | *
317 | * @param dir
318 | * @param filter
319 | */
320 | fun delete(dir: String, filter: FilenameFilter?) {
321 | if (TextUtils.isEmpty(dir))
322 | return
323 | val file = File(dir)
324 | if (!file.exists())
325 | return
326 | if (file.isFile)
327 | file.delete()
328 | if (!file.isDirectory)
329 | return
330 |
331 | var lists: Array? = null
332 | if (filter != null)
333 | lists = file.listFiles(filter)
334 | else
335 | lists = file.listFiles()
336 |
337 | if (lists == null)
338 | return
339 | for (f in lists) {
340 | if (f.isFile) {
341 | f.delete()
342 | }
343 | }
344 | }
345 |
346 | /**
347 | * 获得文件或文件夹的大小
348 | *
349 | * @param path 文件或目录的绝对路径
350 | * @return 返回当前目录的大小 ,注:当文件不存在,为空,或者为空白字符串,返回 -1
351 | */
352 | fun getFileSize(path: String): Long {
353 | if (TextUtils.isEmpty(path)) {
354 | return -1
355 | }
356 | val file = File(path)
357 | return if (file.exists() && file.isFile) file.length() else -1
358 | }
359 | }
360 |
361 |
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/view/LoadView.kt:
--------------------------------------------------------------------------------
1 | package tg.my.core.view
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import android.widget.RelativeLayout
9 | import kt.ktbindadapter.R
10 | import java.util.*
11 |
12 | /**
13 | * 一个方便在多种状态切换的view
14 | */
15 | class LoadView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) {
16 |
17 | private var mEmptyView: View? = null
18 | private var mErrorView: View? = null
19 | private var mLoadingView: View? = null
20 | private var mNoNetworkView: View? = null
21 | private var mContentView: View? = null
22 | private val mEmptyViewResId: Int
23 | private val mErrorViewResId: Int
24 | private val mLoadingViewResId: Int
25 | private val mNoNetworkViewResId: Int
26 | private val mContentViewResId: Int
27 |
28 | /**
29 | * 获取当前状态
30 | */
31 | var viewStatus: Int = 0
32 | private set
33 | private val mInflater: LayoutInflater
34 | private var mOnRetryClickListener: View.OnClickListener? = null
35 |
36 | private val mOtherIds = ArrayList()
37 | private val onLoad: Unit? = null
38 |
39 | init {
40 | val a = context.obtainStyledAttributes(attrs, R.styleable.loadView, defStyleAttr, 0)
41 | mEmptyViewResId = a.getResourceId(R.styleable.loadView_emptyView, R.layout.view_empty)
42 | mErrorViewResId = a.getResourceId(R.styleable.loadView_errorView, R.layout.view_error)
43 | mLoadingViewResId = a.getResourceId(R.styleable.loadView_loadingView, R.layout.view_loding)
44 | mNoNetworkViewResId = a.getResourceId(R.styleable.loadView_noNetworkView, R.layout.view_no_network)
45 | mContentViewResId = a.getResourceId(R.styleable.loadView_contentView, NULL_RESOURCE_ID)
46 | a.recycle()
47 | mInflater = LayoutInflater.from(getContext())
48 | }
49 |
50 | override fun onFinishInflate() {
51 | super.onFinishInflate()
52 | showContent()
53 | }
54 |
55 | override fun onDetachedFromWindow() {
56 | super.onDetachedFromWindow()
57 | clear(mEmptyView, mLoadingView, mErrorView, mNoNetworkView)
58 | mOtherIds?.clear()
59 | if (null != mOnRetryClickListener) {
60 | mOnRetryClickListener = null
61 | }
62 | }
63 |
64 | /**
65 | * 设置重试点击事件
66 | *
67 | * @param onRetryClickListener 重试点击事件
68 | */
69 | fun setOnRetryClickListener(onRetryListener: OnClickListener) {
70 | mOnRetryClickListener= onRetryListener
71 | }
72 |
73 | /**
74 | * 显示空视图
75 | *
76 | * @param layoutId 自定义布局文件
77 | * @param layoutParams 布局参数
78 | */
79 | @JvmOverloads
80 | fun showEmpty(layoutId: Int = mEmptyViewResId, layoutParams: ViewGroup.LayoutParams = DEFAULT_LAYOUT_PARAMS) {
81 | showEmpty(if (null == mEmptyView) inflateView(layoutId) else mEmptyView, layoutParams)
82 | }
83 |
84 | /**
85 | * 显示空视图
86 | *
87 | * @param view 自定义视图
88 | * @param layoutParams 布局参数
89 | */
90 | fun showEmpty(view: View?, layoutParams: ViewGroup.LayoutParams) {
91 | checkNull(view, "Empty view is null.")
92 | checkNull(layoutParams, "Layout params is null.")
93 | viewStatus = STATUS_EMPTY
94 | if (null == mEmptyView) {
95 | mEmptyView = view
96 | val emptyRetryView = mEmptyView!!.findViewById(R.id.cl_empty)
97 | if (null != mOnRetryClickListener && null != emptyRetryView) {
98 | emptyRetryView.setOnClickListener(mOnRetryClickListener)
99 | }
100 | mOtherIds.add(mEmptyView!!.id)
101 | addView(mEmptyView, 0, layoutParams)
102 | }
103 | showViewById(mEmptyView!!.id)
104 | }
105 |
106 | /**
107 | * 显示错误视图
108 | *
109 | * @param layoutId 自定义布局文件
110 | * @param layoutParams 布局参数
111 | */
112 | @JvmOverloads
113 | fun showError(layoutId: Int = mErrorViewResId, layoutParams: ViewGroup.LayoutParams = DEFAULT_LAYOUT_PARAMS) {
114 | showError(if (null == mErrorView) inflateView(layoutId) else mErrorView, layoutParams)
115 | }
116 |
117 | /**
118 | * 显示错误视图
119 | *
120 | * @param view 自定义视图
121 | * @param layoutParams 布局参数
122 | */
123 | fun showError(view: View?, layoutParams: ViewGroup.LayoutParams) {
124 | checkNull(view, "Error view is null.")
125 | checkNull(layoutParams, "Layout params is null.")
126 | viewStatus = STATUS_ERROR
127 | if (null == mErrorView) {
128 | mErrorView = view
129 | val errorRetryView = mErrorView!!.findViewById(R.id.cl_error)
130 | if (null != mOnRetryClickListener && null != errorRetryView) {
131 | errorRetryView.setOnClickListener(mOnRetryClickListener)
132 | }
133 | mOtherIds.add(mErrorView!!.id)
134 | addView(mErrorView, 0, layoutParams)
135 | }
136 | showViewById(mErrorView!!.id)
137 | }
138 |
139 | /**
140 | * 显示加载中视图
141 | *
142 | * @param layoutId 自定义布局文件
143 | * @param layoutParams 布局参数
144 | */
145 | @JvmOverloads
146 | fun showLoading(layoutId: Int = mLoadingViewResId, layoutParams: ViewGroup.LayoutParams = DEFAULT_LAYOUT_PARAMS) {
147 | showLoading(if (null == mLoadingView) inflateView(layoutId) else mLoadingView, layoutParams)
148 | }
149 |
150 | /**
151 | * 显示加载中视图
152 | *
153 | * @param view 自定义视图
154 | * @param layoutParams 布局参数
155 | */
156 | fun showLoading(view: View?, layoutParams: ViewGroup.LayoutParams) {
157 | checkNull(view, "Loading view is null.")
158 | checkNull(layoutParams, "Layout params is null.")
159 | viewStatus = STATUS_LOADING
160 | if (null == mLoadingView) {
161 | mLoadingView = view
162 | mOtherIds.add(mLoadingView!!.id)
163 | addView(mLoadingView, 0, layoutParams)
164 | }
165 | showViewById(mLoadingView!!.id)
166 | }
167 |
168 | /**
169 | * 显示无网络视图
170 | *
171 | * @param layoutId 自定义布局文件
172 | * @param layoutParams 布局参数
173 | */
174 | @JvmOverloads
175 | fun showNoNetwork(layoutId: Int = mNoNetworkViewResId, layoutParams: ViewGroup.LayoutParams = DEFAULT_LAYOUT_PARAMS) {
176 | showNoNetwork(if (null == mNoNetworkView) inflateView(layoutId) else mNoNetworkView, layoutParams)
177 | }
178 |
179 | /**
180 | * 显示无网络视图
181 | *
182 | * @param view 自定义视图
183 | * @param layoutParams 布局参数
184 | */
185 | fun showNoNetwork(view: View?, layoutParams: ViewGroup.LayoutParams) {
186 | checkNull(view, "No network view is null.")
187 | checkNull(layoutParams, "Layout params is null.")
188 | viewStatus = STATUS_NO_NETWORK
189 | if (null == mNoNetworkView) {
190 | mNoNetworkView = view
191 | val noNetworkRetryView = mNoNetworkView!!.findViewById(R.id.cl_no_network)
192 | if (null != mOnRetryClickListener && null != noNetworkRetryView) {
193 | noNetworkRetryView.setOnClickListener(mOnRetryClickListener)
194 | }
195 | mOtherIds.add(mNoNetworkView!!.id)
196 | addView(mNoNetworkView, 0, layoutParams)
197 | }
198 | showViewById(mNoNetworkView!!.id)
199 | }
200 |
201 | /**
202 | * 显示内容视图
203 | */
204 | fun showContent() {
205 | viewStatus = STATUS_CONTENT
206 | if (null == mContentView && mContentViewResId != NULL_RESOURCE_ID) {
207 | mContentView = mInflater.inflate(mContentViewResId, null)
208 | addView(mContentView, 0, DEFAULT_LAYOUT_PARAMS)
209 | }
210 | showContentView()
211 | }
212 |
213 | /**
214 | * 显示内容视图
215 | *
216 | * @param layoutId 自定义布局文件
217 | * @param layoutParams 布局参数
218 | */
219 | fun showContent(layoutId: Int, layoutParams: ViewGroup.LayoutParams) {
220 | showContent(inflateView(layoutId), layoutParams)
221 | }
222 |
223 | /**
224 | * 显示内容视图
225 | *
226 | * @param view 自定义视图
227 | * @param layoutParams 布局参数
228 | */
229 | fun showContent(view: View, layoutParams: ViewGroup.LayoutParams) {
230 | checkNull(view, "Content view is null.")
231 | checkNull(layoutParams, "Layout params is null.")
232 | viewStatus = STATUS_CONTENT
233 | clear(mContentView)
234 | mContentView = view
235 | addView(mContentView, 0, layoutParams)
236 | showViewById(mContentView!!.id)
237 | }
238 |
239 | private fun inflateView(layoutId: Int): View {
240 | return mInflater.inflate(layoutId, null)
241 | }
242 |
243 | private fun showViewById(viewId: Int) {
244 | val childCount = childCount
245 | for (i in 0 until childCount) {
246 | val view = getChildAt(i)
247 | view.visibility = if (view.id == viewId) View.VISIBLE else View.GONE
248 | }
249 | }
250 |
251 | private fun showContentView() {
252 | val childCount = childCount
253 | for (i in 0 until childCount) {
254 | val view = getChildAt(i)
255 | view.visibility = if (mOtherIds.contains(view.id)) View.GONE else View.VISIBLE
256 | }
257 | }
258 |
259 | private fun checkNull(`object`: Any?, hint: String) {
260 | if (null == `object`) {
261 | throw NullPointerException(hint)
262 | }
263 | }
264 |
265 | private fun clear(vararg views: View?) {
266 | if (null == views) {
267 | return
268 | }
269 | try {
270 | for (view in views) {
271 | if (null != view) {
272 | removeView(view)
273 | }
274 | }
275 | } catch (e: Exception) {
276 | e.printStackTrace()
277 | }
278 |
279 | }
280 |
281 |
282 | companion object {
283 | private val DEFAULT_LAYOUT_PARAMS = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
284 | RelativeLayout.LayoutParams.MATCH_PARENT)
285 | val STATUS_CONTENT = 0x00
286 | val STATUS_LOADING = 0x01
287 | val STATUS_EMPTY = 0x02
288 | val STATUS_ERROR = 0x03
289 | val STATUS_NO_NETWORK = 0x04
290 |
291 | private val NULL_RESOURCE_ID = -1
292 | }
293 |
294 |
295 | }
--------------------------------------------------------------------------------
/ktTool/src/main/java/tgs/kttool/util/ToastUtil.kt:
--------------------------------------------------------------------------------
1 | package tgs.kttool.util
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.graphics.PorterDuff
6 | import android.graphics.PorterDuffColorFilter
7 | import android.graphics.Typeface
8 | import android.graphics.drawable.Drawable
9 | import android.graphics.drawable.GradientDrawable
10 | import android.graphics.drawable.NinePatchDrawable
11 | import android.os.Build
12 | import android.support.annotation.CheckResult
13 | import android.support.annotation.ColorInt
14 | import android.support.annotation.DrawableRes
15 | import android.view.LayoutInflater
16 | import android.view.View
17 | import android.widget.ImageView
18 | import android.widget.TextView
19 | import android.widget.Toast
20 | import kt.ktbindadapter.R
21 | import tgs.kttool.ToolApplication.toolAppContext
22 |
23 | object ToastUtil {
24 |
25 |
26 | @ColorInt
27 | private val DEFAULT_TEXT_COLOR = Color.parseColor("#FFFFFF")
28 |
29 | @ColorInt
30 | private val ERROR_COLOR = Color.parseColor("#FD4C5B")
31 |
32 | @ColorInt
33 | private val INFO_COLOR = Color.parseColor("#3F51B5")
34 |
35 | @ColorInt
36 | private val SUCCESS_COLOR = Color.parseColor("#388E3C")
37 |
38 | @ColorInt
39 | private val WARNING_COLOR = Color.parseColor("#FFA900")
40 |
41 | private val TOAST_TYPEFACE = "sans-serif-condensed"
42 |
43 | private var currentToast: Toast? = null
44 |
45 | //*******************************************普通 使用ApplicationContext 方法*********************
46 | /**
47 | * Toast 替代方法 :立即显示无需等待
48 | */
49 | private var mToast: Toast? = null
50 |
51 | fun normal(message: String?) {
52 | normal(toolAppContext, message, Toast.LENGTH_SHORT, null, false)!!.show()
53 | }
54 |
55 | fun normal(message: String?, icon: Drawable) {
56 | normal(toolAppContext, message, Toast.LENGTH_SHORT, icon, true)!!.show()
57 | }
58 |
59 | fun normal(message: String?, duration: Int) {
60 | normal(toolAppContext, message, duration, null, false)!!.show()
61 | }
62 |
63 | fun normal(message: String?, duration: Int, icon: Drawable) {
64 | normal(toolAppContext, message, duration, icon, true)!!.show()
65 | }
66 |
67 | fun normal(message: String?, duration: Int, icon: Drawable, withIcon: Boolean): Toast? {
68 | return custom(toolAppContext, message, icon, DEFAULT_TEXT_COLOR, duration, withIcon)
69 | }
70 |
71 | fun warning(message: String?) {
72 | warning(toolAppContext, message, Toast.LENGTH_SHORT, true)!!.show()
73 | }
74 |
75 | fun warning(message: String?, duration: Int) {
76 | warning(toolAppContext, message, duration, true)!!.show()
77 | }
78 |
79 | fun warning(message: String?, duration: Int, withIcon: Boolean): Toast {
80 | return custom(toolAppContext, message, getDrawable(toolAppContext, R.drawable.ic_error_outline_white_48dp), DEFAULT_TEXT_COLOR, WARNING_COLOR, duration, withIcon, true)
81 | }
82 |
83 | fun info(message: String?) {
84 | info(toolAppContext, message, Toast.LENGTH_SHORT, true)!!.show()
85 | }
86 |
87 | fun info(message: String?, duration: Int) {
88 | info(toolAppContext, message, duration, true)!!.show()
89 | }
90 |
91 | fun info(message: String?, duration: Int, withIcon: Boolean): Toast {
92 | return custom(toolAppContext, message, getDrawable(toolAppContext, R.drawable.ic_info_outline_white_48dp), DEFAULT_TEXT_COLOR, INFO_COLOR, duration, withIcon, true)
93 | }
94 |
95 | fun success(message: String?) {
96 | success(toolAppContext, message, Toast.LENGTH_SHORT, true)!!.show()
97 | }
98 |
99 | fun success(message: String?, duration: Int) {
100 | success(toolAppContext, message, duration, true)!!.show()
101 | }
102 |
103 | fun success(message: String?, duration: Int, withIcon: Boolean): Toast {
104 | return custom(toolAppContext, message, getDrawable(toolAppContext, R.drawable.ic_check_white_48dp), DEFAULT_TEXT_COLOR, SUCCESS_COLOR, duration, withIcon, true)
105 | }
106 |
107 | fun error(message: String?) {
108 | error(toolAppContext, message, Toast.LENGTH_SHORT, true)!!.show()
109 | }
110 | //===========================================使用ApplicationContext 方法=========================
111 |
112 | //*******************************************常规方法********************************************
113 |
114 | fun error(message: String?, duration: Int) {
115 | error(toolAppContext, message, duration, true)!!.show()
116 | }
117 |
118 | fun error(message: String?, duration: Int, withIcon: Boolean): Toast {
119 | return custom(toolAppContext, message, getDrawable(toolAppContext, R.drawable.ic_clear_white_48dp), DEFAULT_TEXT_COLOR, ERROR_COLOR, duration, withIcon, true)
120 | }
121 |
122 | @CheckResult
123 | fun normal(context: Context, message: String?): Toast? {
124 | return normal(context, message, Toast.LENGTH_SHORT, null, false)
125 | }
126 |
127 | @CheckResult
128 | fun normal(context: Context, message: String?, icon: Drawable): Toast? {
129 | return normal(context, message, Toast.LENGTH_SHORT, icon, true)
130 | }
131 |
132 | @CheckResult
133 | fun normal(context: Context, message: String?, duration: Int): Toast? {
134 | return normal(context, message, duration, null, false)
135 | }
136 |
137 | @CheckResult
138 | fun normal(context: Context, message: String?, duration: Int, icon: Drawable): Toast? {
139 | return normal(context, message, duration, icon, true)
140 | }
141 |
142 | @CheckResult
143 | fun normal(context: Context, message: String?, duration: Int, icon: Drawable?, withIcon: Boolean): Toast? {
144 | return custom(context, message, icon, DEFAULT_TEXT_COLOR, duration, withIcon)
145 | }
146 |
147 | @CheckResult
148 | fun warning(context: Context, message: String?): Toast? {
149 | return warning(context, message, Toast.LENGTH_SHORT, true)
150 | }
151 |
152 | @CheckResult
153 | fun warning(context: Context, message: String?, duration: Int): Toast? {
154 | return warning(context, message, duration, true)
155 | }
156 |
157 | @CheckResult
158 | fun warning(context: Context, message: String?, duration: Int, withIcon: Boolean): Toast? {
159 | return custom(context, message, getDrawable(context, R.drawable.ic_error_outline_white_48dp), DEFAULT_TEXT_COLOR, WARNING_COLOR, duration, withIcon, true)
160 | }
161 |
162 | @CheckResult
163 | fun info(context: Context, message: String?): Toast? {
164 | return info(context, message, Toast.LENGTH_SHORT, true)
165 | }
166 |
167 | @CheckResult
168 | fun info(context: Context, message: String?, duration: Int): Toast? {
169 | return info(context, message, duration, true)
170 | }
171 |
172 | @CheckResult
173 | fun info(context: Context, message: String?, duration: Int, withIcon: Boolean): Toast? {
174 | return custom(context, message, getDrawable(context, R.drawable.ic_info_outline_white_48dp), DEFAULT_TEXT_COLOR, INFO_COLOR, duration, withIcon, true)
175 | }
176 |
177 | @CheckResult
178 | fun success(context: Context, message: String?): Toast? {
179 | return success(context, message, Toast.LENGTH_SHORT, true)
180 | }
181 |
182 | @CheckResult
183 | fun success(context: Context, message: String?, duration: Int): Toast? {
184 | return success(context, message, duration, true)
185 | }
186 |
187 | @CheckResult
188 | fun success(context: Context, message: String?, duration: Int, withIcon: Boolean): Toast? {
189 | return custom(context, message, getDrawable(context, R.drawable.ic_check_white_48dp), DEFAULT_TEXT_COLOR, SUCCESS_COLOR, duration, withIcon, true)
190 | }
191 |
192 | @CheckResult
193 | fun error(context: Context, message: String?): Toast? {
194 | return error(context, message, Toast.LENGTH_SHORT, true)
195 | }
196 |
197 | //===========================================常规方法============================================
198 |
199 | @CheckResult
200 | fun error(context: Context, message: String?, duration: Int): Toast? {
201 | return error(context, message, duration, true)
202 | }
203 |
204 | @CheckResult
205 | fun error(context: Context, message: String?, duration: Int, withIcon: Boolean): Toast? {
206 | return custom(context, message, getDrawable(context, R.drawable.ic_clear_white_48dp), DEFAULT_TEXT_COLOR, ERROR_COLOR, duration, withIcon, true)
207 | }
208 |
209 | @CheckResult
210 | fun custom(context: Context, message: String?, icon: Drawable?, @ColorInt textColor: Int, duration: Int, withIcon: Boolean): Toast? {
211 | return custom(context, message, icon, textColor, -1, duration, withIcon, false)
212 | }
213 |
214 | //*******************************************内需方法********************************************
215 |
216 | @CheckResult
217 | fun custom(context: Context, message: String?, @DrawableRes iconRes: Int, @ColorInt textColor: Int, @ColorInt tintColor: Int, duration: Int, withIcon: Boolean, shouldTint: Boolean): Toast? {
218 | return custom(context, message, getDrawable(context, iconRes), textColor, tintColor, duration, withIcon, shouldTint)
219 | }
220 |
221 | @CheckResult
222 | fun custom(context: Context, message: String?, icon: Drawable?, @ColorInt textColor: Int, @ColorInt tintColor: Int, duration: Int, withIcon: Boolean, shouldTint: Boolean): Toast {
223 | if (currentToast == null) {
224 | currentToast = Toast(context)
225 | }
226 | val toastLayout = (context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(R.layout.toast_layout, null)
227 | val toastIcon = toastLayout.findViewById(R.id.toast_icon)
228 | val toastTextView = toastLayout.findViewById(R.id.toast_text)
229 | val drawableFrame: Drawable?
230 | if (shouldTint) {
231 | drawableFrame = tint9PatchDrawableFrame(context, tintColor)
232 | } else {
233 | drawableFrame = getDrawable(context, R.drawable.toast_frame)
234 | }
235 | setBackground(toastLayout, drawableFrame)
236 |
237 | if (withIcon) {
238 | if (icon == null) {
239 | throw IllegalArgumentException("Avoid passing 'icon' as null if 'withIcon' is set to true") as Throwable
240 | }
241 | setBackground(toastIcon, icon)
242 | } else {
243 | toastIcon.setVisibility(View.GONE)
244 | }
245 | toastTextView.setTextColor(textColor)
246 | toastTextView.setText(message)
247 | toastTextView.setTypeface(Typeface.create(TOAST_TYPEFACE, Typeface.NORMAL))
248 | currentToast!!.view = toastLayout
249 | currentToast!!.duration = duration
250 | return currentToast!!
251 | }
252 |
253 | private fun tint9PatchDrawableFrame(context: Context, @ColorInt tintColor: Int): Drawable {
254 | val toastDrawable = getDrawable(context, R.drawable.toast_frame)!!
255 | if (toastDrawable is GradientDrawable || toastDrawable is NinePatchDrawable) {
256 | toastDrawable.colorFilter = PorterDuffColorFilter(tintColor, PorterDuff.Mode.SRC_IN)
257 | }
258 | return toastDrawable
259 | }
260 | //===========================================内需方法============================================
261 |
262 |
263 | //******************************************系统 Toast 替代方法***************************************
264 |
265 | fun setBackground(view: View, drawable: Drawable?) {
266 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
267 | view.background = drawable
268 | } else {
269 | view.setBackgroundDrawable(drawable)
270 | }
271 | }
272 |
273 | fun getDrawable(context: Context, @DrawableRes id: Int): Drawable? {
274 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
275 | context.getDrawable(id)
276 | } else {
277 | context.resources.getDrawable(id)
278 | }
279 | }
280 |
281 | }
--------------------------------------------------------------------------------