Using Linkify in ListView's ArrayAdapter causes RuntimeException

前端 未结 3 1370
说谎
说谎 2021-01-16 09:18

I have a TextView in my ArrayAdapter that may contain some hyperlinks. For those links I use Linkify:

public View get         


        
相关标签:
3条回答
  • 2021-01-16 09:40

    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) {
                // ...
            }
        });
    

    You must have initialized the context variable above with the application context, like this:

        Context context = getApplicationContext();
    

    To avoid the error, you should have initialized it with your Activity instance instead:

        Context context = this;
    

    Or, if your code is in a Fragment:

        Context context = getActivity();
    
    0 讨论(0)
  • 2021-01-16 09:46

    In your Activity.Java while binding your list with adapter

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

    In YourAdapter.java in Constructor make sure it's Activity not Context

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

    And, use this code for your textview in your adapter for Linkify.

    holder.yourTextView.setLinksClickable(true);
    holder.yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
    Linkify.addLinks(holder.yourTextView, Linkify.ALL);
    holder.yourTextView.setAutoLinkMask(Linkify.ALL);
    
    0 讨论(0)
  • 2021-01-16 09:52

    If you are interested to open a link, you can use

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

    this would would work fine for you inside a ListView.

    0 讨论(0)
提交回复
热议问题