在ListView的ArrayAdapter中使用Linkify会导致RuntimeException

时间:2012-08-05 14:54:24

标签: android android-listview android-arrayadapter linkify

我的TextView中有一个ArrayAdapter,可能包含一些超链接。对于这些链接,我使用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;
}

但是因为在ArrayAdapter中添加了Linkify,我得到一个例外说明:

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)

我该如何使这项工作?我无法想到另一种选择。

3 个答案:

答案 0 :(得分:5)

查看日志中的异常,您似乎在分配ArrayAdapter时使用了应用程序上下文。例如,如果您的代码与以下内容类似:

    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 context = getApplicationContext();

为避免错误,您应该使用Activity实例进行初始化:

    Context context = this;

或者,如果您的代码位于Fragment

    Context context = getActivity();

答案 1 :(得分:0)

如果您有兴趣打开链接,可以使用

String text = "<a href=\"http://www.google.co.in/\">Google</a>";
holder.content.setText(Html.fromHtml(text));
holder.content.setMovementMethod(LinkMovementMethod.getInstance());

这可以在ListView中正常工作。

答案 2 :(得分:0)

在使用适配器

绑定列表时,在Activity.Java中
YourAdapter yourAdapter = new YourAdapter(YourCurrentActivityName.this, YourArrayList);
yourListView.setAdapter(yourAdapter); 

在构造函数中的YourAdapter.java中,确保它的活动不是上下文

public YourAdapter(Activity context, YourArrayList list){
    this.context = context;
    this.list = list;
}

并且,在适配器中使用此代码作为Linkify的textview。

holder.yourTextView.setLinksClickable(true);
holder.yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
Linkify.addLinks(holder.yourTextView, Linkify.ALL);
holder.yourTextView.setAutoLinkMask(Linkify.ALL);