在 ListView 的 ArrayAdapter 中使用 Linkify 会导致 RuntimeException [英] Using Linkify in ListView's ArrayAdapter causes RuntimeException

查看:37
本文介绍了在 ListView 的 ArrayAdapter 中使用 Linkify 会导致 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆