将onClick添加到RecyclerView以打开RecyclerView项目的URL

问题描述

我有一个要解析的JSON,并在RecyclerView对象中使用它。 JSON包含指向相关新闻报道的URL,我不确定如何从适配器获取URL并在按下项目时打开链接。我在网上搜索的大部分内容似乎都不适用于我,因此我非常感谢您的帮助。这是相关代码和JSON数据示例。

JSON

    {
    "status": "ok","totalResults": 65,"articles": [
        {
            "source": {
                "id": "the-wall-street-journal","name": "The Wall Street Journal"
            },"author": null,"title": "Gyms Brace for Fewer Members As At-Home fitness Rises During Pandemic","description": "How might the coronavirus pandemic transform the fitness industry? To find out WSJ spoke with the CEO of Planet fitness,an independent gym owner and an industry analyst to learn about what we can expect for the future of fitness.","url": "https://www.wsj.com/video/gyms-brace-for-fewer-members-as-at-home-fitness-rises-during-pandemic/80E5B6D3-8297-43B6-8C3A-872038A5ADA6.html?mod=hp_lead_pos12","urlToImage": "http://m.wsj.net/video/20200910/091020cultureshiftgyms1/091020cultureshiftgyms1_1280x720.jpg","publishedAt": "2020-09-11T12:52:44.9999066Z","content": "Inside the Tear of God: A Unique House on Crete That Filters the Sun\r\n9/7/2020For his home on Crete,Greeces largest island,George Kalykakis wanted something unique. He got a sculptural structure,n… [+117 chars]"
        },{
            "source": {
                "id": "cbc-news","name": "CBC News"
            },"author": "CBC News","title": "Coronavirus: What's happening in Canada and around the world on Friday | CBC News","description": "A doctor who has been working with some of Calgary's most vulnerable citizens during the COVID-19 pandemic is worried homeless shelters won't have enough space to keep everyone safe once the cold weather hits.","url": "http://www.cbc.ca/news/canada/world-canada-covid-19-sept-11-1.5720126","urlToImage": "https://i.cbc.ca/1.5720172.1599823518!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/covid-alta-homeless-20200903.jpg","publishedAt": "2020-09-11T12:37:22.4755242Z","content": "The latest:\r\n<ul><li>Calgary doctor worried lack of shelter space Could hamper pandemic efforts over winter.</li><li>Quebec to ban karaoke after event linked to 80 cases of COVID-19.</li><li>UN warns… [+8319 chars]"
        }
    ]
}

NewsFragment.Java

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.linearlayoutmanager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;

public class NewsFragment extends Fragment {

    View view;
    RecyclerView recyclerView;
    JSONArray news;
    String newsUrl;

    public NewsFragment(JSONArray data,String url) {
        news = data;
        newsUrl = url;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.view_page,container,false);
        recyclerView = view.findViewById(R.id.recyclerView2);
        linearlayoutmanager layoutManager = new linearlayoutmanager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(false);
        RecyclerView.Adapter<Customlistadapter.ListViewHolder> mAdapter = new Customlistadapter(news,newsUrl);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setonClickListener((AdapterView.OnItemClickListener) (parent,view,position,id) -> {

            String url;// THIS IS WHERE I NEED TO GET THE URL FROM THE CLICKED ITEM
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        });
        return view;
    }

}

Customlistadapter.java

import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;

import java.text.NumberFormat;

public class Customlistadapter extends RecyclerView.Adapter<Customlistadapter.ListViewHolder> {

    private JSONArray mDataset;
    private String murl;

    static class ListViewHolder extends RecyclerView.ViewHolder {

        // each data item that we need to populate
        TextView textView;
        TextView textView2;
        ImageView imageView;
        ListViewHolder(LinearLayout v) {
            super(v);
            textView = v.findViewById(R.id.name);
            textView2 = v.findViewById(R.id.cases);
            imageView = v.findViewById(R.id.image);
        }

    }

    // Provide a suitable constructor (depends on the kind of dataset)
    Customlistadapter(JSONArray myDataset,String url) {
        mDataset = myDataset;
        murl = url;
    }

    // Create new views (invoked by the layout manager)
    @NonNull
    @Override
    public Customlistadapter.ListViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
        // create a new view
        LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_view,parent,false);

        // TextView v = (TextView) linearLayout.findViewById(R.id.info_text);

        return new ListViewHolder(linearLayout);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ListViewHolder holder,int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element

        String textViewString = "";
        String textView2String = "";
        String url = "";

        try {
            textViewString = mDataset.getJSONObject(position).getString("title");
            textView2String = mDataset.getJSONObject(position).getString("description");
            url = mDataset.getJSONObject(position).getString("url");
            holder.textView.setText(textViewString);
            holder.textView2.setText(textView2String);
        } catch (JSONException e) {
            e.printstacktrace();
        }

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.length();
    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)