【问题标题】:How to get item position for recycle-view如何获取回收视图的项目位置
【发布时间】:2018-04-23 19:09:04
【问题描述】:

我是一名 Android 程序员,我正在开发一个使用 RSS 提要从网络获取新闻的新闻应用程序,我的代码工作正常!但是当我点击任何新闻打开新活动显示新闻详细信息时我不会?我正在使用回收视图我如何获得点击项目的位置并传递新闻?.. 这是我的 ReadRss:

public class ReadRss extends AsyncTask<Void, Void, Void> {
Context context;
String address = "http://www.sciencemag.org/rss/news_current.xml";
ProgressDialog progressDialog;
ArrayList<FeedItem> feedItems;
RecyclerView recyclerView;
URL url;

public ReadRss(Context context, RecyclerView recyclerView) {
    this.recyclerView = recyclerView;
    this.context = context;
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading...");
}

//before fetching of rss statrs show progress to user
@Override
protected void onPreExecute() {
    progressDialog.show();
    super.onPreExecute();
}


//This method will execute in background so in this method download rss feeds
@Override
protected Void doInBackground(Void... params) {
    //call process xml method to process document we downloaded from getData() method
    ProcessXml(Getdata());

    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    progressDialog.dismiss();
    FeedsAdapter adapter = new FeedsAdapter(context, feedItems);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.addItemDecoration(new VerticalSpace(20));
    recyclerView.setAdapter(adapter);
}

// In this method we will process Rss feed  document we downloaded to parse useful information from it
private void ProcessXml(Document data) {
    if (data != null) {
        feedItems = new ArrayList<>();
        Element root = data.getDocumentElement();
        Node channel = root.getChildNodes().item(1);
        NodeList items = channel.getChildNodes();
        for (int i = 0; i < items.getLength(); i++) {
            Node cureentchild = items.item(i);
            if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
                FeedItem item = new FeedItem();
                NodeList itemchilds = cureentchild.getChildNodes();
                for (int j = 0; j < itemchilds.getLength(); j++) {
                    Node cureent = itemchilds.item(j);
                    if (cureent.getNodeName().equalsIgnoreCase("title")) {
                        item.setTitle(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("description")) {
                        item.setDescription(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("pubDate")) {
                        item.setPubDate(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("link")) {
                        item.setLink(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("media:thumbnail")) {
                        //this will return us thumbnail url
                        String url = cureent.getAttributes().item(0).getTextContent();
                        item.setThumbnailUrl(url);
                    }
                }
                feedItems.add(item);


            }
        }
    }
}

//This method will download rss feed document from specified url
public Document Getdata() {
    try {
        url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDoc = builder.parse(inputStream);
        return xmlDoc;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

} 我的 FeedsAdapter:

public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.MyViewHolder> {
ArrayList<FeedItem>feedItems;
Context context;
public FeedsAdapter(Context context, ArrayList<FeedItem>feedItems){
    this.feedItems=feedItems;
    this.context=context;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view= LayoutInflater.from(context).inflate(R.layout.custum_row_news_item,parent,false);
    MyViewHolder holder=new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    YoYo.with(Techniques.FadeIn).playOn(holder.cardView);
    FeedItem current=feedItems.get(position);
    holder.Title.setText(current.getTitle());
    holder.Description.setText(current.getDescription());
    holder.Date.setText(current.getPubDate());
    Picasso.with(context).load(current.getThumbnailUrl()).into(holder.Thumbnail);

}



@Override
public int getItemCount() {
    return feedItems.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView Title,Description,Date;
    ImageView Thumbnail;
    CardView cardView;
    public MyViewHolder(View itemView) {
        super(itemView);
        Title= (TextView) itemView.findViewById(R.id.title_text);
        Description= (TextView) itemView.findViewById(R.id.description_text);
        Date= (TextView) itemView.findViewById(R.id.date_text);
        Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img);
        cardView= (CardView) itemView.findViewById(R.id.cardview);
    }
}

}

【问题讨论】:

标签: android android-recyclerview rss-reader


【解决方案1】:

我不确定我是否理解你。但是要检查用户何时点击新闻,您必须将以下代码添加到您的 FeedsAdapter

@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
  holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FeedItem item = feedItems.get(position);
            //start your activity here
        }
    });
  //other code
}

【讨论】:

    【解决方案2】:

    所以你可以使用回调接口来传递数据,比如

    interface DisplayNews{
    void newsDetail(int position);// any name as per your requirement 
    }
    

    然后在您的基本活动/片段中实现该接口,例如

    class NewsActivity implements DisplayNews{
    @Override
     void newsDetail(int position){
      // get your list item/element from list using postion and pass that into  intent to new activity
    }
    }
    

    并在您的适配器中更改适配器承包商和一些小代码,例如

    public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.MyViewHolder> {
    ArrayList<FeedItem>feedItems;
    Context context;
    private DisplayNews callback;
    public FeedsAdapter(Context context, ArrayList<FeedItem>feedItems,DisplayNews callback){
        this.feedItems=feedItems;
        this.context=context;
        this.callback=callback;
    
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(context).inflate(R.layout.custum_row_news_item,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }
    
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        YoYo.with(Techniques.FadeIn).playOn(holder.cardView);
        FeedItem current=feedItems.get(position);
        holder.Title.setText(current.getTitle());
        holder.Description.setText(current.getDescription());
        holder.Date.setText(current.getPubDate());
        Picasso.with(context).load(current.getThumbnailUrl()).into(holder.Thumbnail);
    holder.itemView.setOnClickListener(view -> callback.newsDetail(holder.getAbsoluteAdapterPosition());
    
    }
    @Override
    public int getItemCount() {
        return feedItems.size();
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView Title,Description,Date;
        ImageView Thumbnail;
        CardView cardView;
        public MyViewHolder(View itemView) {
            super(itemView);
            Title= (TextView) itemView.findViewById(R.id.title_text);
            Description= (TextView) itemView.findViewById(R.id.description_text);
            Date= (TextView) itemView.findViewById(R.id.date_text);
            Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img);
            cardView= (CardView) itemView.findViewById(R.id.cardview);
        }
    }
    ,,, 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多