我在TextView中有一些哈希标签,以’#’开头 示例:“#one#two Hello World #three”. 我希望这些哈希标签可单独点击并打开一个活动并在该活动中获取此文本. 因此,这些哈希作为链接工作并打开
示例:“#one#two Hello World #three”.
我希望这些哈希标签可单独点击并打开一个活动并在该活动中获取此文本.
因此,这些哈希作为链接工作并打开一个活动.标签也不固定意味着可以是任何文本.同时将哈希标记的颜色更改为红色,其余标记的颜色将为黑色
示例:#one#two Hello World #three
根据您的要求修改以下内容.使用SpannableStringString s ="#one #Two Hello World #three"; String split[] = s.split("#"); TextView_tv = (TextView) findViewById( R.id.tv ); for(int i=1;i<split.length;i++) { SpannableString ss1= new SpannableString("#"+split[i]); ss1.setSpan(new MyClickableSpan(""+i), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ss1.setSpan(newForegroundColorSpan(Color.RED),0,1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); _tv.append(ss1); _tv.append(" "); } _tv.setMovementMethod(LinkMovementMethod.getInstance()); class MyClickableSpan extends ClickableSpan{ String clicked; public MyClickableSpan(String string) { super(); clicked =string; } public void onClick(View tv) { if(clicked.equals("1")) { Toast.makeText(getApplicationContext(), "One",1000).show(); } else if(clicked.equals("2")) { Toast.makeText(getApplicationContext(), "Two",1000).show(); } else { Toast.makeText(getApplicationContext(), "Three",1000).show(); } } @Override public void updateDrawState(TextPaint ds) { ds.setUnderlineText(false); // set to false to remove underline } } }
抓住模拟器
在每个哈希点击显示吐司一,二和三.而不是吐司开始一个新的活动.
编辑:
如果你想点击字符串
ss1.setSpan(new MyClickableSpan(""+i,split[i]), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
然后
String clicked; String astring; public MyClickableSpan(String check,String actualstring) { super(); clicked =check; astring =actualstring; // pass this to next activity using intent }
然后
public void onClick(View tv) { if(clicked.equals("1")) { Toast.makeText(getApplicationContext(), astring,1000).show(); } else if(clicked.equals("2")) { Toast.makeText(getApplicationContext(), astring,1000).show(); } else { Toast.makeText(getApplicationContext(), astring,1000).show(); } }