TextView
「#」で始まるハッシュタグがいくつかあります
例:「#one#two Hello World #three」。
これらのハッシュタグを個別にクリック可能にして、アクティビティを開いて、そのアクティビティでこのテキストを取得したいと考えています。
したがって、これらのハッシュはリンクとして機能し、アクティビティを開きます。また、タグは固定されていないため、任意のテキストを指定できます。また、ハッシュタグの色を赤に変更し、残りのタグの色を黒にします
必要に応じて以下を変更します。使うSpannableString
String 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
}
}
}
スナップオンエミュレータ
各ハッシュをクリックすると、トースト 1、2、3 が表示されます。乾杯する代わりに、新しいアクティビティを開始します。
編集:
文字列をクリックしたい場合
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();
}
}