package cn.sinata.xldutils.utils
|
|
import android.app.Activity
|
import android.content.ContentUris
|
import android.content.Context
|
import android.content.Intent
|
import android.database.Cursor
|
import android.graphics.Bitmap
|
import android.graphics.drawable.Drawable
|
import android.net.Uri
|
import android.os.Build
|
import android.os.Environment
|
import android.os.StatFs
|
import android.provider.DocumentsContract
|
import android.provider.MediaStore
|
import android.text.*
|
import android.text.style.ForegroundColorSpan
|
import android.util.Log
|
import android.view.View
|
import android.view.inputmethod.InputMethodManager
|
import android.webkit.*
|
import android.widget.EditText
|
import android.widget.TextView
|
import android.widget.Toast
|
import androidx.core.content.ContextCompat
|
import cn.sinata.xldutils.utils.ViewClickDelay.SPACE_TIME
|
import cn.sinata.xldutils.utils.ViewClickDelay.hash
|
import cn.sinata.xldutils.utils.ViewClickDelay.lastClickTime
|
import com.kuanzhai.driver.base.InnerJsInterface
|
import com.kuanzhai.driver.base.MyApplication
|
import org.jetbrains.anko.internals.AnkoInternals
|
import java.text.DecimalFormat
|
import java.util.*
|
|
/**
|
*
|
*/
|
|
fun Any.getSDFreeSize(): Long {
|
//取得SD卡文件路径
|
val path = Environment.getExternalStorageDirectory()
|
val sf = StatFs(path.path)
|
//获取单个数据块的大小(Byte)
|
val blockSize: Long
|
//空闲的数据块的数量
|
val freeBlocks: Long
|
if (Build.VERSION.SDK_INT >= 18) {
|
blockSize = sf.blockSizeLong
|
freeBlocks = sf.availableBlocksLong
|
} else {
|
blockSize = sf.blockSize.toLong()
|
freeBlocks = sf.availableBlocks.toLong()
|
}
|
//返回SD卡空闲大小
|
//return freeBlocks * blockSize; //单位Byte
|
//return (freeBlocks * blockSize)/1024; //单位KB
|
return freeBlocks * blockSize / 1024 / 1024 //单位MB
|
}
|
|
fun hideKeyboard(view: View) {
|
val inputMethodManager: InputMethodManager =
|
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
if (inputMethodManager != null) {
|
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
|
}
|
}
|
|
//设置double精确到小数点后1位
|
fun doubleOne(price: Double): String? {
|
return String.format("%.1f", price)
|
}
|
|
fun doubleTwo(price: Double): String? {
|
return String.format("%.2f", price)
|
}
|
|
fun String.isVideo():Boolean{
|
return this.endsWith("mp4") || this.endsWith("AVI") || this.endsWith("MP4") || this.endsWith("avi")|| this.endsWith("mov")
|
}
|
|
|
fun doubleOneNone(f: Double): String{
|
val df = DecimalFormat("#.0")
|
return df.format(f)
|
}
|
|
|
fun WebView.setWeb(url: String) {
|
val settings = this.settings
|
settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
|
settings.defaultTextEncodingName = "utf-8" //设置编码格式
|
settings.useWideViewPort = true //设置此属性,可任意比例缩放
|
settings.loadWithOverviewMode = true // 页面支持缩放:
|
settings.builtInZoomControls = true
|
settings.useWideViewPort = false //将图片调整到适合webview的大小
|
settings.setSupportZoom(false) //支持缩放
|
settings.supportMultipleWindows() //多窗口
|
settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK //关闭webview中缓存
|
settings.allowFileAccess = true //设置可以访问文件
|
settings.setNeedInitialFocus(true) //当webview调用requestFocus时为webview设置节点
|
settings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
|
settings.loadsImagesAutomatically = true //支持自动加载图片
|
settings.javaScriptEnabled = true
|
settings.domStorageEnabled = true
|
this.isScrollContainer = false
|
this.isScrollbarFadingEnabled = false
|
this.scrollBarStyle = View.SCROLLBARS_OUTSIDE_OVERLAY
|
this.addJavascriptInterface(InnerJsInterface(), "HTMLOUT")
|
this!!.webChromeClient = object : WebChromeClient() {
|
override fun onReceivedTitle(
|
view: WebView?,
|
title: String?
|
) {
|
super.onReceivedTitle(view, title)
|
}
|
}
|
this!!.webViewClient = object : WebViewClient() {
|
override fun onPageFinished(
|
view: WebView?,
|
url: String?
|
) {
|
super.onPageFinished(view, url)
|
}
|
|
override fun onPageStarted(
|
view: WebView?,
|
url: String?,
|
favicon: Bitmap?
|
) {
|
super.onPageStarted(view, url, favicon)
|
}
|
|
override fun shouldOverrideUrlLoading(
|
view: WebView?,
|
url: String?
|
): Boolean {
|
Utils.systemErr(url)
|
if (!TextUtils.isEmpty(url)) {
|
this@setWeb.loadUrl(url!!)
|
}
|
return true
|
}
|
|
override fun shouldInterceptRequest(
|
view: WebView?,
|
request: WebResourceRequest?
|
): WebResourceResponse? {
|
return super.shouldInterceptRequest(view, request)
|
}
|
}
|
if (url.startsWith("http")) {
|
this.loadUrl(url)
|
} else {
|
val sHead =
|
"<html><head><meta name=\"viewport\" content=\"width=device-width, " + "initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" />" + "<style>img{max-width:100% !important;height:auto !important;}</style>" + "<style>body{max-width:100% !important;}</style>" + "</head><body>"
|
this.loadDataWithBaseURL(null, sHead + url, "text/html", "utf-8", null)
|
}
|
}
|
|
|
|
fun Activity.getUrlPath(imageUri: Uri?): String? {
|
if (imageUri == null) {
|
return null
|
}
|
Log.e("mmp", "文档uri:" + imageUri)
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(
|
this,
|
imageUri
|
)
|
) {
|
if (isExternalStorageDocument(imageUri)) {
|
val docId = DocumentsContract.getDocumentId(imageUri)
|
Log.e("mmp", "外存文件,文档id:" + docId)
|
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
|
val type = split[0]
|
if ("primary".equals(type, ignoreCase = true)) {
|
return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
|
}
|
} else if (isDownloadsDocument(imageUri)) {
|
val id = DocumentsContract.getDocumentId(imageUri)
|
Log.e("mmp", "下载文件,文档id:" + id)
|
return try {
|
val contentUri = ContentUris.withAppendedId(
|
Uri.parse("content://downloads/public_downloads"),
|
java.lang.Long.valueOf(id)
|
)
|
getDataColumn(this, contentUri, null, null)
|
} catch (e: NumberFormatException) {
|
null
|
}
|
} else if (isMediaDocument(imageUri)) {
|
val docId = DocumentsContract.getDocumentId(imageUri)
|
Log.e("mmp", "多媒体文件,文档id:" + docId)
|
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
|
val type = split[0]
|
var contentUri: Uri? = null
|
if ("image" == type) {
|
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
|
} else if ("video" == type) {
|
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
|
} else if ("audio" == type) {
|
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
|
}
|
val selection = MediaStore.Images.Media._ID + "=?"
|
val selectionArgs = arrayOf(split[1])
|
return getDataColumn(this, contentUri, selection, selectionArgs)
|
}
|
} // MediaStore (and general)
|
else if ("content".equals(imageUri.scheme, ignoreCase = true)) {
|
Log.e("mmp", "content文件")
|
// Return the remote address
|
if (isGooglePhotosUri(imageUri))
|
return imageUri.lastPathSegment
|
return getDataColumn(this, imageUri, null, null)
|
} else if ("file".equals(imageUri.scheme, ignoreCase = true)) {
|
Log.e("mmp", "file")
|
return imageUri.path
|
}// File
|
return null
|
}
|
|
/**
|
* @param uri The Uri to check.
|
* @return Whether the Uri authority is Google Photos.
|
*/
|
fun isGooglePhotosUri(uri: Uri): Boolean = "com.google.android.apps.photos.content" == uri.authority
|
|
/**
|
* @param uri The Uri to check.
|
* *
|
* @return Whether the Uri authority is ExternalStorageProvider.
|
*/
|
fun isExternalStorageDocument(uri: Uri): Boolean =
|
"com.android.externalstorage.documents" == uri.authority
|
|
/**
|
* @param uri The Uri to check.
|
* *
|
* @return Whether the Uri authority is DownloadsProvider.
|
*/
|
fun isDownloadsDocument(uri: Uri): Boolean =
|
"com.android.providers.downloads.documents" == uri.authority
|
|
/**
|
* @param uri The Uri to check.
|
* *
|
* @return Whether the Uri authority is MediaProvider.
|
*/
|
fun isMediaDocument(uri: Uri): Boolean = "com.android.providers.media.documents" == uri.authority
|
|
fun getDataColumn(
|
context: Context,
|
uri: Uri?,
|
selection: String?,
|
selectionArgs: Array<String>?
|
): String? {
|
if (uri == null) {
|
return null
|
}
|
var cursor: Cursor? = null
|
val column = MediaStore.Images.Media.DATA
|
val projection = arrayOf(column)
|
try {
|
cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
|
if (cursor != null && cursor.moveToFirst()) {
|
val index = cursor.getColumnIndexOrThrow(column)
|
return cursor.getString(index)
|
}
|
} finally {
|
if (cursor != null)
|
cursor.close()
|
}
|
return null
|
}
|
|
fun toast(msg: String){
|
Toast.makeText(MyApplication.appContext, msg, Toast.LENGTH_SHORT).show()
|
}
|
|
|
fun callPhone(context: Context, phone: String) {
|
// if (phone.trim { it <= ' ' }.isEmpty()) { // ToastUtils.showShortToast(context,"请输入手机号");
|
// return
|
// }
|
val intent = Intent(
|
Intent.ACTION_DIAL,
|
Uri.parse("tel:$phone")
|
)
|
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
context.startActivity(intent)
|
}
|
|
fun Activity.getVersionName(): String {
|
return try {
|
val manager = this.packageManager
|
val info = manager.getPackageInfo(this.packageName, 0)
|
info.versionName
|
} catch (e: Exception) {
|
e.printStackTrace()
|
"--"
|
}
|
|
}
|
|
object ViewClickDelay {
|
var hash: Int = 0
|
var lastClickTime: Long = 0
|
var SPACE_TIME: Long = 1000
|
}
|
|
infix fun View.clickDelay(clickAction: () -> Unit) {
|
this.setOnClickListener {
|
if (this.hashCode() != hash) {
|
hash = this.hashCode()
|
lastClickTime = System.currentTimeMillis()
|
clickAction()
|
} else {
|
val currentTime = System.currentTimeMillis()
|
if (currentTime - lastClickTime > SPACE_TIME) {
|
lastClickTime = System.currentTimeMillis()
|
clickAction()
|
}
|
}
|
}
|
}
|
|
fun View.gone() {
|
this.visibility = View.GONE
|
}
|
|
|
fun View.visible() {
|
this.visibility = View.VISIBLE
|
}
|
|
|
fun View.invisible() {
|
this.visibility = View.INVISIBLE
|
}
|
|
fun TextView.textColor(context: Context, resourse: Int) {
|
this.setTextColor(ContextCompat.getColor(context, resourse))
|
}
|
|
fun EditText.getContent(): String {
|
return this.text.toString().trim()
|
}
|
|
|
fun TextView.getContent(): String {
|
return this.text.toString().trim()
|
}
|
|
fun TextView.setDrawableLeft(drawableResourseId: Int) {
|
val topAct: Drawable = context.resources.getDrawable(drawableResourseId)
|
this.setCompoundDrawablesWithIntrinsicBounds(topAct, null, null, null)
|
}
|
|
|
fun TextView.setDrawableBottom(drawableResourseId: Int) {
|
val topAct: Drawable = context.resources.getDrawable(drawableResourseId)
|
this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, topAct)
|
}
|
|
fun TextView.setDrawableRight(drawableResourseId: Int) {
|
val topAct: Drawable = context.resources.getDrawable(drawableResourseId)
|
this.setCompoundDrawablesWithIntrinsicBounds(null, null, topAct, null)
|
}
|
|
fun TextView.setDrawableTop(drawableResourseId: Int) {
|
val topAct: Drawable = context.resources.getDrawable(drawableResourseId)
|
this.setCompoundDrawablesWithIntrinsicBounds(null, topAct, null, null)
|
}
|
|
fun TextView.setDrawableNull() {
|
this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
|
}
|
|
|
fun TextView.setBold() {
|
this.paint.isFakeBoldText = true
|
}
|
|
|
fun TextView.setBoldFalse() {
|
this.paint.isFakeBoldText = false
|
}
|
|
fun TextView.setColor(context: Context, resourse: Int) {
|
this.setTextColor(ContextCompat.getColor(context, resourse))
|
}
|
|
fun TextView.setColorAndSelect(select: Boolean, context: Context, resourse: Int) {
|
this.isSelected = select
|
this.setTextColor(ContextCompat.getColor(context, resourse))
|
}
|
|
fun EditText.getString(): String {
|
return this.text.toString().trim()
|
}
|
|
fun EditText.setTextChange(onClick: (text: String) -> Unit) {
|
this.addTextChangedListener(object : TextWatcher {
|
override fun afterTextChanged(s: Editable?) {
|
}
|
|
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
|
}
|
|
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
|
var s = this@setTextChange.text.toString().trim()
|
onClick(s)
|
}
|
})
|
}
|
|
var View.backgroundDrawable: Drawable?
|
inline get() = background
|
set(value) = setBackgroundDrawable(value)
|
|
var View.backgroundColorResource: Int
|
@Deprecated(
|
AnkoInternals.NO_GETTER,
|
level = DeprecationLevel.ERROR
|
) get() = AnkoInternals.noGetter()
|
set(colorId) = setBackgroundColor(context.resources.getColor(colorId))
|
|
fun sysErr(msg: Any?) {
|
Log.e("OkTrip----trip", "--------" + msg)
|
}
|
|
fun getFormatOne(value: Double?):String{
|
return Formatter().format("%.1f", value).toString()
|
}
|
fun getFormatTwo(value: Double?):String{
|
return Formatter().format("%.2f", value).toString()
|
}
|
|
fun TextView.setColorBuild(context: Context, content: String, color: Int, start: Int, end: Int){
|
var span = SpannableStringBuilder(content);
|
span.setSpan(
|
ForegroundColorSpan(ContextCompat.getColor(context, color)),
|
start,
|
end,
|
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
)
|
this.text = span
|
}
|
|
|
fun TextView.setColorBuild(
|
context: Context,
|
content: String,
|
color: Int,
|
start: Int,
|
end: Int,
|
start1: Int,
|
end1: Int
|
){
|
var span = SpannableStringBuilder(content);
|
span.setSpan(
|
ForegroundColorSpan(ContextCompat.getColor(context, color)),
|
start,
|
end,
|
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
)
|
span.setSpan(
|
ForegroundColorSpan(ContextCompat.getColor(context, color)),
|
start1,
|
end1,
|
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
)
|
this.text = span
|
}
|
|
//多个参数
|
//showCityPop(object :( String, String) -> Unit {
|
// override fun invoke(province: String, city: String) {
|
//
|
// }
|
//})
|