美文网首页Android开发
TextView长按复制功能失效

TextView长按复制功能失效

作者: 卓技卓品 | 来源:发表于2021-12-09 19:04 被阅读0次

应用中RecyclerView列表显示的动态简介需添加长按复制的功能,以此提升用户的体验。 本来使用Android自带的功能就能满足该需求,无需自己实现,方式很简单,一句话解决:

TextView.setTextIsSelectable(true);

但是我这个项目出现无法复制的清空。 仔细体验几次发现,长按时的确出现了震动反馈,但并没有出现选择条,说明该代码确实添加到控件上。但是没有出现复制条一定是哪里拦截或者阻止了。 打印日志发现系统报了异常:

TextView does not support text selection. Action mode cancelled.

就拿着该异常去网上找解决办法,发现不只是我本人遇到了该问题。好多人提问,网上的回答却是千奇百怪、各种不靠谱。 但是有一个人的答案被遗漏在无人关注的角落,本着试试的心态测试发现真的可行,就拿过来分享。 其实很简单,应该是Android的系统bug:在TextView外部嵌套一个布局,让TextView不要使用android:layout_width="match_parent",改成使用android:layout_width="wrap_content"即可。 更改后发现完美解决。 最终代码如下: 修复之前相关代码:

<TextView
  android:id="@+id/tv_helinfo_comment_introduction"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/iv_helinfo_comment_avatar"
  android:background="@drawable/sayhi_content_bg"
  android:textColor="#999999"/>

修复后相关代码:

<LinearLayout
  android:id="@+id/ll_helinfo_comment_introduction"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/iv_helinfo_comment_avatar"
  android:layout_marginLeft="10dp"
   android:layout_marginRight="10dp"
  android:background="@drawable/sayhi_content_bg">
    <TextView
    android:id="@+id/tv_helinfo_comment_introduction"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:textColor="#131313"/>
</LinearLayout>

添加复制功能的代码:

holder.tvIntroduction = (TextView) view.findViewById(R.id.tv_helinfo_comment_introduction);
holder.tvIntroduction.setTextIsSelectable(true);

相关文章

网友评论

    本文标题:TextView长按复制功能失效

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