package com.example.testdemo.kt
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.Intent.ACTION_CALL
import android.content.res.Resources
import android.net.Uri
import android.text.Editable
import android.text.Spannable
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import java.text.SimpleDateFormat
import java.util.*
```
eg:使用方式如下
```
```
fun EditText.superAddTextChangedListener(content: String,afterTextChanged: (s: Editable?) -> Unit) {
if (this.tag is TextWatcher) {
this.removeTextChangedListener(this.tag as TextWatcher)
this.clearFocus()
}
val watcher = object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(p0: Editable?) {
afterTextChanged.invoke(p0)
}
}
this.setText(content)
this.addTextChangedListener(watcher)
this.tag = watcher
}
```
fun EditText.superAddTextChangedListener2(afterTextChanged: (s: Editable?) -> Unit) {
val watcher = object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(p0: Editable?) {
if (this@superAddTextChangedListener2.hasFocus()) {
afterTextChanged.invoke(p0)
}
}
}
this.setOnFocusChangeListener { view, hasFocus ->
if (hasFocus) {
this.addTextChangedListener(watcher)
} else {
this.removeTextChangedListener(watcher)
}
}
}
fun CheckBox.superOnCheckedChangeListener(OnCheckedChangeListened: (CompoundButton, Boolean) -> Unit) {
this.setOnCheckedChangeListener(null)
val checkedChange = CompoundButton.OnCheckedChangeListener { p0, p1 -> OnCheckedChangeListened.invoke(p0, p1) }
this.setOnCheckedChangeListener(checkedChange)
}
fun RadioGroup.superOnCheckedChangeListener(block: (RadioGroup, Int) -> Unit) {
this.setOnCheckedChangeListener(null)
this.setOnCheckedChangeListener { radioGroup, id ->
block.invoke(radioGroup, id)
}
}
```
fun EditText.isEmpty(): Boolean {
return this.text.isNullOrEmpty()
}
fun EditText.selectionEnd() {
this.setSelection(this.text.length)
}
fun EditText.setTextAndSelectionEnd(@StringRes resId: Int) {
this.setText(resId)
selectionEnd()
}
fun EditText.setTextAndSelectionEnd(text: CharSequence) {
this.setText(text)
selectionEnd()
}
fun EditText.listenerTextChange(onChange: (s: CharSequence?, count: Int) -> 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) {
onChange(s, count)
}
})
}
```
fun Any?.printToLog(tag: String = "DEBUG_LOG") {
Log.d(tag, toString())
}
val Any?.isNull get() = this == null
fun Any?.ifNull(block: () -> Unit) = run {
if (this == null) {
block()
}
}
val ViewGroup.children: List<View>
get() = (0 until childCount).map { getChildAt(it) }
val Float.px
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, this, Resources.getSystem().displayMetrics)
val Float.dp
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics)
val Float.sp
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this, Resources.getSystem().displayMetrics)
val Int.dp
get() = this.toFloat().dp
fun String.toDate(format: String = "yyyy-MM-dd HH:mm:ss"): Date? {
val dateFormatter = SimpleDateFormat(format, Locale.getDefault())
return dateFormatter.parse(this)
}
fun Date.toStringFormat(format: String = "yyyy-MM-dd HH:mm:ss"): String {
val dateFormatter = SimpleDateFormat(format, Locale.getDefault())
return dateFormatter.format(this)
}
val String.isDigitOnly: Boolean
get() = matches(Regex("^\d*$"))
val String.isAlphabeticOnly: Boolean
get() = matches(Regex("^[a-zA-Z]*$"))
val String.isAlphanumericOnly: Boolean
get() = matches(Regex("^[a-zA-Z\d]*$"))
fun Activity.hideKeyboard() {
val imm: InputMethodManager =
getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
val view = currentFocus ?: View(this)
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
fun Fragment.hideKeyboard() {
activity?.apply {
val imm: InputMethodManager =
getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
val view = currentFocus ?: View(this)
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
fun Fragment.showToast(message: String) {
Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
}
fun Fragment.showToast(@StringRes message: Int) {
Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
}
fun Activity.showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
fun Activity.showToast(@StringRes message: Int) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
fun View.getLInWindow(): IntArray {
val locations = IntArray(2)
getLocationInWindow(locations)
return locations
}
fun View.getLocationXInWindow(): Int {
return getLInWindow()[0]
}
fun View.getLocationYInWindow(): Int {
return getLInWindow()[1]
}
fun View.getLOnScreen(): IntArray {
val locations = IntArray(2)
getLocationOnScreen(locations)
return locations
}
fun View.getLocationXOnScreen(): Int {
return getLOnScreen()[0]
}
fun View.getLocationYOnScreen(): Int {
return getLOnScreen()[1]
}
val Context.screenWidthPx: Int
get() = resources.displayMetrics.widthPixels
val Context.screenHeightPx: Int
get() = resources.displayMetrics.heightPixels
fun Context.makeCall(number: String): Boolean {
try {
val intent = Intent(ACTION_CALL, Uri.parse("tel:$number"))
startActivity(intent)
return true
} catch (e: Exception) {
return false
}
}
fun TextView.setColorOfSubstring(substring: String, color: Int) {
try {
val spannable = android.text.SpannableString(text)
val start = text.indexOf(substring)
spannable.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, color)), start, start + substring.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannable
} catch (e: Exception) {
Log.d("ViewExtensions", "exception in setColorOfSubstring, text=$text, substring=$substring", e)
}
}
fun TextView.copyStr(): Boolean {
return try {
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val mClipData = ClipData.newPlainText("Label", this.text)
cm.setPrimaryClip(mClipData)
true
} catch (e: java.lang.Exception) {
false
}
}