1

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;
}

但是因为Linkify在 ArrayAdapter 中添加了 ,所以我得到一个异常说:

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)

我怎样才能使这项工作?我想不出替代方案。

4

3 回答 3

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();
于 2012-08-11T01:42:42.450 回答
0

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

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

这对您在 ListView 中会很好。

于 2012-08-08T11:47:37.513 回答
0

在您的 Activity.Java 中,同时将您的列表与适配器绑定

YourAdapter yourAdapter = new YourAdapter(YourCurrentActivityName.this, YourArrayList);
yourListView.setAdapter(yourAdapter); 

在构造函数的 YourAdapter.java 中,确保它是 Activity 而不是 Context

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

并且,将此代码用于 Linkify 适配器中的文本视图。

holder.yourTextView.setLinksClickable(true);
holder.yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
Linkify.addLinks(holder.yourTextView, Linkify.ALL);
holder.yourTextView.setAutoLinkMask(Linkify.ALL);
于 2017-07-26T11:20:42.707 回答