10 个对于Android开发者有用的Kotlin扩展函数#1

10 个对于Android开发者有用的Kotlin扩展函数

使用扩展函数来提高安卓开发体验
logo

什么是扩展功能?

Kotlin 中的扩展函数允许您向现有类添加新功能,而无需继承它或修改类本身。这是从类定义外部扩展类功能的便捷方式。

Log

您可以any object使用此扩展功能轻松地在 logcat 中编写。您不必担心将任何对象转换为字符串。可以用默认标签写,也可以通过自定义标签在logcat中区分。

import android.util.Log

fun Any?.printToLog(tag: String = "DEBUG_LOG") {
    
    
    Log.d(tag, toString())
}

用法

val text = "This is text"
 text.printToLog() 

val user = User( 
    name = "John" , 
    id = 1
 ) 
user.printToLog() // 使用默认日志标签
user.printToLog(tag = "USER_INFO" ) / / 带有自定义日志标签

View#visiable,invisible,gone

在 Android 中,我们总是需要处理视图。因此,很明显,我们必须使用视图可见性来显示或隐藏特定的文本视图、图像视图和任何其他视图。因此,此功能有助于可见性处理。您可以直接将gone()visible()invisible()函数应用于单个操作。

但是,如果您必须处理特定条件下的可见性,则可以使用goneIfvisibleIfinvisibleIf函数。此函数使用中缀表示法的概念来增加代码的可读性。

import android.view.View

fun View.gone() = run {
    
     visibility = View.GONE }

fun View.visible() = run {
    
     visibility = View.VISIBLE }

fun View.invisible() = run {
    
     visibility = View.INVISIBLE }

infix fun View.visibleIf(condition: Boolean) =
    run {
    
     visibility = if (condition) View.VISIBLE else View.GONE }

infix fun View.goneIf(condition: Boolean) =
    run {
    
     visibility = if (condition) View.GONE else View.VISIBLE }
    
infix fun View.invisibleIf(condition: Boolean) =
    run {
    
     visibility = if (condition) View.INVISIBLE else View.VISIBLE }

用法

view.gone() 
view.visible() 
view.invisible() 

// dataFound、loading、condition 应该是有效的布尔表达式
view goneIf dataFound 
view visibleIf loading 
view invisibleIf condition

Toast

Toast,向用户显示消息或发出警告是一件简单的事情。为此,您必须使用 Toast 类的 makeText 函数并传递上下文和其他内容以及使用 show 函数来显示。

因此,此扩展功能允许您简单地传递一条消息,然后您的 toast 就会显示出来。此函数是在 Activity 和 Fragment 范围内创建的。因此,您必须在该范围内使用它。您还可以仅使用字符串 ID 来使用字符串资源文件中的文本。

import android.app.Activity
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment

fun Fragment.toast(message: String) {
    
    
    Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
}

fun Fragment.toast(@StringRes message: Int) {
    
    
    Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
}

fun Activity.toast(message: String) {
    
    
    Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}

fun Activity.toast(@StringRes message: Int) {
    
    
    Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}

用法

toast( "这是Toast消息" ) 
toast(R.string.toast_message)

snackbar

此功能可帮助您在视图顶部显示一个 snackbar 以进行简单的消息显示,并且您还可以根据需要更改持续时间。您必须在视图或根视图上使用此功能。

import android.view.View
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar

fun View.snackbar(message: String, duration: Int = Snackbar.LENGTH_LONG) {
    
    
    Snackbar.make(this, message, duration).show()
}

fun View.snackbar(@StringRes message: Int, duration: Int = Snackbar.LENGTH_LONG) {
    
    
    Snackbar.make(this, message, duration).show()
}

用法

rootView.snackbar( "This is snackbar message" ) 
rootView.snackbar(R.string.snackbar_message) 

// 自定义持续时间长度
rootView.snackbar( "This is snackbar message" , duration = Snackbar.LENGTH_SHORT)

hidekeyboard

如果您正在处理用户操作,或者如果您想在任何特定情况下以编程方式隐藏键盘,那么隐藏键盘可能会让人头疼,那么此功能将很有用。您必须简单地调用hideKeyboard()活动或片段范围。

import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment

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)
    }
}

用法

hideKeyboard()

dp 和 px 转换

有时,您必须从代码文件中动态修改视图,而不是从 XML 中对其进行修复。例如,您可能必须为特定场景更改视图宽度和高度,或者您必须修改边距或填充。因此,在那种情况下,您必须将像素传递给这些函数。但是您希望根据与密度无关的像素 (dp) 标准有更多的了解。

因此,此属性可帮助您进行px to dp和dp to px转换。您可以简单地使用 px 属性将 dp 转换为 px,并使用 dp 属性将 px 转换为 dp。

import android.content.res.Resources

// Convert px to dp
val Int.dp: Int
    get() = (this / Resources.getSystem().displayMetrics.density).toInt()

//Convert dp to px
val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

用法

params.setMargins( 16.px , 16.px , 16.px , 16.px )

数字及字母检查

此属性允许您检查字符串。当您只想验证数字、字母或字符串文本中的字母数字时,这会很有用。检查示例以获得更多理解。它基于正则表达式。

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]*\$"))

用法

val isValidNumber = "1234" .isDigitOnly // return true
val isValid = "1234abc" .isDigitOnly // return false
val isOnlyAlphabetic = "abcABC" .isAlphabeticOnly // return true
val isOnlyAlphabetic2 = "abcABC123" .isAlphabeticOnly // return false
val isOnlyAlphanumeric = "abcABC123" .isAlphanumericOnly // return true
val isOnlyAlphanumeric2 = "abcABC@123." .isAlphanumericOnly // return false

isNull

isNull 将应用于任何属性。每当您要检查任何对象的 null 相等性时,都会使用此属性。此属性将增加代码的可读性。您可以使用obj.isNull而不是obj == null

val Any?.isNull get() = this == null

用法

if (obj.isNull) {
    
    
    // Run if object is null
} else {
    
    
    // Run if object is not null
}

ifNull

如果你想在特定对象为空时运行一些代码怎么办?在这种情况下,通常,您必须使用具有 null 相等性的 if 条件。但是,除此之外,您还可以使用此功能。当该特定对象为空时,它将运行该块。这个概念就像其他作用域函数一样。

fun Any?.ifNull(block: () -> Unit) = run {
    
    
    if (this == null) {
    
    
        block()
    }
}

用法

obj.ifNull {
    
     
    // Write code
}

日期格式

在 Android 中处理日期时,我们必须对服务器日期和用户可读日期进行一些自定义。为此,我们通常使用辅助函数进行转换。

但是,在这里,我们可以直接在字符串到字符串到日期的转换中应用这个函数,我们可以在日期上使用这个函数来进行日期到字符串的转换。在这里,我已经通过了默认格式。但你可以改变它。您可以根据您的要求传递自定义格式。

import java.text.SimpleDateFormat
import java.util.*

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 currentDate = Date().toStringFormat()
val currentDate2 = Date().toStringFormat(format = "dd-MM-yyyy")
val date = "2023-01-01".toDate(format = "yyyy-MM-dd")

结论

我希望所提供的扩展函数对简化和优化您的代码很有用。随意修改它们以满足您的个人需求并将它们包含在您的项目中。

猜你喜欢

转载自blog.csdn.net/u011897062/article/details/130880363