在ListView的ArrayAdapter中使用Linkify会导致RuntimeException [英] Using Linkify in ListView's ArrayAdapter causes RuntimeException
问题描述
我的ArrayAdapter
中有一个TextView
,其中可能包含一些超链接.对于那些链接,我使用Linkify
:
I have a TextView
in my ArrayAdapter
that may contain some hyperlinks. For those links I use Linkify
:
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
rowView = inflater.inflate(R.layout.list_item_2, null);
holder = new ViewHolder();
holder.content = (TextView) rowView.findViewById(R.id.postContent);
holder.date = (TextView) rowView.findViewById(R.id.postDate);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.content.setText(contents.get(position));
holder.date.setText(dates.get(position));
Linkify.addLinks(holder.content, Linkify.ALL);
return rowView;
}
但是因为Linkify
已添加到ArrayAdapter中,所以我得到了一个例外:
But because the Linkify
is added in the ArrayAdapter, I get an exception saying this:
08-05 16:42:16.715: E/AndroidRuntime(20598): FATAL EXCEPTION: main
08-05 16:42:16.715: E/AndroidRuntime(20598): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
08-05 16:42:16.715: E/AndroidRuntime(20598): at android.app.ContextImpl.startActivity(ContextImpl.java:921)
08-05 16:42:16.715: E/AndroidRuntime(20598): at android.content.ContextWrapper.startActivity(ContextWrapper.java:283)
08-05 16:42:16.715: E/AndroidRuntime(20598): at android.text.style.URLSpan.onClick(URLSpan.java:62)
我该如何进行这项工作?我想不出另一种选择.
How can I make this work? I can't think of an alternative.
推荐答案
查看日志中的异常,似乎在分配ArrayAdapter
时使用了应用程序上下文.例如,如果您的代码类似于以下内容:
Looking at the exception in the log, it seems that you used the application context when you allocate your ArrayAdapter
. For example, if your code looks similar to the following:
listView.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1,
data) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// ...
}
});
您必须已使用应用程序上下文初始化了上面的 context 变量,如下所示:
You must have initialized the context variable above with the application context, like this:
Context context = getApplicationContext();
为避免该错误,您应该使用Activity
实例对其进行初始化:
To avoid the error, you should have initialized it with your Activity
instance instead:
Context context = this;
或者,如果您的代码在Fragment
中:
Or, if your code is in a Fragment
:
Context context = getActivity();
这篇关于在ListView的ArrayAdapter中使用Linkify会导致RuntimeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!