在 TextView 中长按链接时显示上下文菜单 [英] Show context menu when link is long pressed in TextView

查看:15
本文介绍了在 TextView 中长按链接时显示上下文菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TextView,它的 MovementMethod 设置为 LinkMovementMethod.添加到 TextView 的文本是普通文本和 URL 的组合.对于 URL,我想在长按 URL 以执行复制地址等操作时提供上下文菜单.我查看了 LinkMovementMethod 的源代码,但它似乎没有任何我可以覆盖的长按相关代码.关于如何实现这一目标的任何想法?

I have a TextView with its MovementMethod set to LinkMovementMethod. Text added to the TextView is a combination of normal text and URLs. For URLs, I would like to offer a context menu when the URL is long pressed for doing things such as copying the address. I've had a look at the source for LinkMovementMethod but it doesn't seem to have any long pressed related code I could override. Any ideas on how to go around achieving this?

推荐答案

你可以简单地使用 registerForContextMenu eg:

You can simply use registerForContextMenu eg:

    TextView tv = new TextView(this);
    registerForContextMenu(tv);

然后重写onCreateContextMenu来创建菜单

and then override the onCreateContextMenu to create a menu

@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
            // Create your context menu here
    menu.setHeaderTitle("Context Menu");
    menu.add(0, v.getId(), 0, "Action 1");        
}

您可以使用视图的 ID 传递给按下菜单项时发生的事件,以区分哪个视图调用了该事件.

where you can use the ID of the view to pass on to the events that occur on pressing of a menu item, in order to differentiate which view called the event.

@Override
public boolean onContextItemSelected(MenuItem item) {
    // Call your function to preform for buttons pressed in a context menu
    // can use item.getTitle() or similar to find out button pressed
    // item.getItemID() will return the v.getID() that we passed before

}

这篇关于在 TextView 中长按链接时显示上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆