使用零食栏扩展功能时出现Lint错误



我有以下扩展函数来减少一点代码,并避免在显示小吃栏时忘记持续时间:

fun Fragment.showSnackbar(text: String, length: Int = Snackbar.LENGTH_SHORT) {
view?.run { Snackbar.make(this, text, length).show() }
}

但是lint给了我以下错误:

Error: Must be one of: BaseTransientBottomBar.LENGTH_INDEFINITE, BaseTransientBottomBar.LENGTH_SHORT, BaseTransientBottomBar.LENGTH_LONG or value must be ≥ 1 (was -1) [WrongConstant]
view?.run { Snackbar.make(this, textResId, length).show() }
~~~~~~

如果你传递一个自定义长度参数,它应该是一个int>=0,并且它正在检测默认参数是一个自定义参数,而不是一个系统/类参数,但它是(LENGTH_SHORT,这是-1)。

如果长度参数是BaseTransientBottomBar.Duration类型(这是一个接口符号来设置长度参数的可能值),它编译得很好,但我不知道如何将其分配为默认值。

有任何方法可以避免lint错误或设置类型为BaseTransientBottomBar.Duration的默认值吗?

—EDIT: after apply @rahat方法:

fun Fragment.showSnackbar(text: String, @BaseTransientBottomBar.Duration length: Int = Snackbar.LENGTH_SHORT) {
view?.run { Snackbar.make(this, text, length).show() }
}

错误:

[PATH]/DesignExt.kt:18: Error: Must be one of: BaseTransientBottomBar.LENGTH_INDEFINITE, BaseTransientBottomBar.LENGTH_SHORT, BaseTransientBottomBar.LENGTH_LONG [WrongConstant]
fun Fragment.showSnackbar(text: String, @BaseTransientBottomBar.Duration length: Int = Snackbar.LENGTH_SHORT) {
                    ~~~~~~~~~~~~~~~~~~~~~

由于被调用方法的签名如下

@NonNull
public static Snackbar make(
@NonNull View view, @NonNull CharSequence text, @Duration int duration)

Snackbar

public class Snackbar extends BaseTransientBottomBar<Snackbar>

最后Duration的签名为

@RestrictTo(LIBRARY_GROUP)
@IntDef({LENGTH_INDEFINITE, LENGTH_SHORT, LENGTH_LONG})
@IntRange(from = 1)
@Retention(RetentionPolicy.SOURCE)
public @interface Duration {}

所以传递的值必须是来自Duration的值之一,即使是,lint来了,因为参数没有注释,可以接受任何Int的值,但是当你注释时,当你用不同于Duration中存在的值调用你的方法时,它会在那个地方给你警告,它可能导致RuntimException如果传递的值不是其中之一。

Try with this,

fun Fragment.showSnackbar(text: String, @BaseTransientBottomBar.Duration length: Int = Snackbar.LENGTH_SHORT) {
view?.run { Snackbar.make(this, text, length).show() }
}

最后我避免了在lint.xml文件中添加警告'WrongConstant'的错误。如果它是文件中唯一的内容,它将是:

android {     
lintOptions {          
warning "WrongConstant"      
} 
}

最新更新