[英]click link in textview
我有文本视图,我想将文本设置为链接以指向站点,但问题是我无法单击:
Grades = (TextView) findViewById(R.id.textView9);
Grades.setText(Html.fromHtml(course.getString(TAG_Grade)));
Grades.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
WebView webView; webView.setWebViewClient(new WebViewClient()
{
}webView.loadUrl(course.getString(TAG_Grade)); });
和xml:
<TextView
android:id="@+id/textView9"
android:layout_marginLeft="110dp"
android:layout_marginTop="365dp"
android:textColor="#000"
android:textSize="14sp"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:autoLink="web"
android:onClick="onClick"
/>
知道course.getString(TAG_Grade)
将从数据库获取URL,但是它不起作用
问题是什么?
使用了这个android:clickable="true"
<TextView
android:id="@+id/textView9"
android:layout_marginLeft="110dp"
android:layout_marginTop="365dp"
android:textColor="#000"
android:textSize="14sp"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:autoLink="web"
android:onClick="onClick"
/>
单击视图后 ,您尝试链接它,将其从onClick中删除。
您的处理方式错误。
尝试这个:
String userCanSeeThis = "Your Website Name";
String url = course.getString(TAG_Grade);
TextView grades = (TextView) findViewById(R.id.textView9);
grades.setText(userCanSeeThis);
addLinks(Grades, userCanSeeThis, url);
使用此辅助方法:
/**
* @param textView
* textView who's text you want to change
* @param linkThis
* a regex of what text to turn into a link
* @param toThis
* the url you want to send them to
*/
public static void addLinks(TextView textView, String linkThis, String toThis) {
Pattern pattern = Pattern.compile(linkThis);
String scheme = toThis;
android.text.util.Linkify.addLinks(textView, pattern, scheme, new MatchFilter() {
@Override
public boolean acceptMatch(CharSequence s, int start, int end) {
return true;
}
}, new TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
return "";
}
});
}
此外,如果你设置onClickListener
在你的代码grades.setOnClickListener
那么你不需要android:onClick=""
在你的XML
除了使用Linkify
我更喜欢以下行:
Html.fromHtml(course.getString(TAG_Grade));
TextView myWebSite = new TextView(this);
myWebSite .setText("http://www.google.com/");
Linkify.addLinks(myWebSite , Linkify.WEB_URLS);
您已经收到有关Linkify的足够答案,但是您的代码中还有一个微妙的错误爬网:
您误将属性他的android:onClick
与方法onClick
一个的View.onClickListener
:
android:onClick
属性的工作方式如下:
单击该视图时在此View上下文中调用的方法的名称。 该名称必须对应于一个公共方法,该方法只使用View类型的一个参数。 例如,如果您指定android:onClick =“ sayHello”,则必须声明上下文(通常是Activity)的公共void sayHello(View v)方法。
至于View.onClickListener
提供的onClick
方法:
view.setOnClickListener(...)
单击此视图时,注册要调用的回调。 如果该视图不可单击,它将变为可单击。
这将允许您覆盖该功能:
public abstract void onClick (View v)
单击视图时调用该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.