是否可以在文本视图的某些部分添加onclick?例如,我的代码是这样的,
String content = "Hello this a test.. For more details contact @Peter";
someTextView.setText(content);
我想为“@Peter”添加一个onClick事件。这可能吗?
TIA。
答案 0 :(得分:7)
简单: - )
SpannableString link = makeLinkSpan("@Peter", new View.OnClickListener() {
@Override
public void onClick(View v) {
// Peforme Click
}
});
String content = "Hello this a test.. For more details contact";
someTextView.setText(content);
someTextView.append(link);
而makeLinkSpan()
方法是
private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {
SpannableString link = new SpannableString(text);
link.setSpan(new ClickableString(listener), 0, text.length(),
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
return link;
}
ClickableString
类
private static class ClickableString extends ClickableSpan {
private View.OnClickListener mListener;
public ClickableString(View.OnClickListener listener) {
mListener = listener;
}
@Override
public void onClick(View v) {
mListener.onClick(v);
}
}
答案 1 :(得分:4)
在你的Xml中加上这个,android:clickable="true"
在你的活动中使用像这样,
textView.setOnClickListener(new View.OnClickListener(){
public void onClick(){
}
}
答案 2 :(得分:3)
感谢@ user370305的回复。但是他在答案中错过了一些代码片段。为了别人的利益,我正在粘贴整个代码,对我有用,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView someTextView = (TextView)findViewById(R.id.someTextView);
String content = "Hello this a test.. For more details contact";
someTextView.setText(content);
SpannableString link = makeLinkSpan("@Peter", new View.OnClickListener() {
@Override
public void onClick(View v) {
//Do something here..
}
});
someTextView.append(link);
}
makeLinksFocusable(someTextView);
}
private void makeLinksFocusable(TextView tv) {
MovementMethod m = tv.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tv.getLinksClickable()) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {
SpannableString link = new SpannableString(text);
link.setSpan(new ClickableString(listener), 0, text.length(),
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
return link;
}
private static class ClickableString extends ClickableSpan {
private View.OnClickListener mListener;
public ClickableString(View.OnClickListener listener) {
mListener = listener;
}
@Override
public void onClick(View v) {
mListener.onClick(v);
}
}
答案 3 :(得分:2)
这可能会使用Java代码:
someTextView.setOnClickListener(new View.OnClickListener(){
public void onClick(){
//Do Stuff
}
});
但首先请确保将其设置为可点击。
someTextView.setClickable(true);
答案 4 :(得分:1)
试试这个:
SpannableString str = new SpannableString("@Peter");
str.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
}
}, 0, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
然后将str
附加到TextView。
您还需要在TextView上调用setMovementMethod(LinkMovementMethod.getInstance());