美文网首页Android开发Android技术知识Android开发
【Android】让AlertDialog的文本支持选择

【Android】让AlertDialog的文本支持选择

作者: 来一斤BUG | 来源:发表于2023-11-14 19:13 被阅读0次

实现效果

长按AlertDialog的文本支持选择


弹窗文本长按选择

代码

AlertDialog的默认文本无法直接长按选择,但是为了这么一个小功能使用自定义布局有点得不偿失。这里我提供一种方法:

import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.annotation.IdRes

/**
 * 允许弹窗文本选择
 */
fun enableMessageSelection(
    alertDialog: AlertDialog,
    @IdRes messageTextViewId: Int = android.R.id.message,
) {
    alertDialog.window?.findViewById<TextView>(messageTextViewId)?.setTextIsSelectable(true)
}

/**
 * 禁止弹窗文本选择
 */
fun disableMessageSelection(
    alertDialog: AlertDialog,
    @IdRes messageTextViewId: Int = android.R.id.message,
) {
    alertDialog.window?.findViewById<TextView>(messageTextViewId)?.setTextIsSelectable(false)
}

说明

AlertDialog默认的TextView有一个名为message的ID,但它是属于安卓系统自带的,所以我们需要使用android.R.id.message获取它。接着就可以调用setTextIsSelectable(Boolean)方法设置其是否可以选择了。

相关文章

网友评论

    本文标题:【Android】让AlertDialog的文本支持选择

    本文链接:https://www.haomeiwen.com/subject/vxvjwdtx.html