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

实现效果

长按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)方法设置其是否可以选择了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容