简体   繁体   English

RecyclerView - 从我的 ViewHolder 获取对象

[英]RecyclerView - Getting Objects from my ViewHolder

I'm creating a RecyclerView that accepts a list of Match objects.我正在创建一个接受匹配对象列表的 RecyclerView。 I have set an onClickListener for the listItem.我已经为 listItem 设置了一个 onClickListener。 I want to set the Match to active when I click on this listItem.当我单击此列表项时,我想将匹配设置为活动状态。 How do I get access to the Match object that's being stored in a particular listItem when I click on it.当我单击它时,如何访问存储在特定 listItem 中的 Match 对象。

Here is my Adapter/ViewHolder class for the RecyclerView:这是我用于 RecyclerView 的 Adapter/ViewHolder 类:

package com.checkinsystems.ez_score.utils;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.checkinsystems.ez_score.EditMatchActivity;
import com.checkinsystems.ez_score.MainActivity;
import com.checkinsystems.ez_score.MatchActivity;
import com.checkinsystems.ez_score.R;
import com.checkinsystems.ez_score.model.Match;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;



public class MatchItemAdapter extends RecyclerView.Adapter<MatchItemAdapter.ViewHolder> {

    private List<Match> mMatches;
    private final Context mContext;

    public MatchItemAdapter(Context context, List<Match> items) {
        this.mContext = context;
        this.mMatches = items;
    }

    @Override
    public MatchItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(mContext);
        View itemView = inflater.inflate(R.layout.list_item_match, parent, false);
        ViewHolder viewHolder = new ViewHolder(itemView);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final MatchItemAdapter.ViewHolder holder, int position) {
        Match match = mMatches.get(position);

        try {
            holder.tvName.setText(match.getMatchName());
            holder.tvDate.setText(match.getMatchDate());
            holder.imageView.findViewById(R.id.imageView);
            holder.hiddenMatchId.setText(match.getMatchId());
            holder.container.findViewById(R.id.list_item_container);

            Typeface bold = Typeface.create("san-serif", Typeface.BOLD);

            SharedPreferences sharedPreferences = mContext.getSharedPreferences(
                    MY_GLOBAL_PREFS, mContext.MODE_PRIVATE);
            String currentMatchName = sharedPreferences.getString(CURRENT_MATCH_NAME, "current_match_name");


            String itemName = holder.tvName.getText().toString();

            if (itemName.equals(currentMatchName)) {
                holder.tvName.setTypeface(bold);
                holder.container.setBackgroundColor(Color.parseColor("#a4a4a4"));
                holder.tvName.setTextSize(24);
                holder.matchIsActive = true;


                SharedPreferences.Editor editor = mContext.getSharedPreferences(MY_GLOBAL_PREFS, mContext.MODE_PRIVATE).edit();
                editor.putString(CURRENT_MATCH_ID, match.getMatchId());
                editor.putString(CURRENT_MATCH_NAME, match.getMatchName());
                editor.putString(CURRENT_MATCH_CLUB_ID, match.getClubId());
                editor.putString(CURRENT_MATCH_DATE, match.getMatchDate());
                editor.putString(CURRENT_MATCH_LEVEL, match.getMatchLevel());
                int spinnerPos;
                switch (match.getMatchLevel()){
                    case "I":
                        spinnerPos = 0;
                        break;
                    case "II":
                        spinnerPos = 1;
                        break;
                    case "III":
                        spinnerPos = 2;
                        break;
                    case "IV":
                        spinnerPos = 3;
                        break;
                    default:
                        spinnerPos = 0;
                }
                editor.putInt(POSITION_OF_SPINNER, spinnerPos);
                editor.apply();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

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


    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tvName;
        public TextView tvDate;
        public ImageView imageView;
        public TextView hiddenMatchId;
        public View container;

        boolean matchIsActive = false;


        public ViewHolder(final View itemView) {
            super(itemView);

            tvName = (TextView) itemView.findViewById(R.id.match_name);
            tvDate = (TextView) itemView.findViewById(R.id.match_date);
            imageView = (ImageView) itemView.findViewById(R.id.imageView);
            hiddenMatchId = (TextView) itemView.findViewById(R.id.match_id_hidden);
            container = (View) itemView.findViewById(R.id.list_item_container);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    final PopupMenu popup = new PopupMenu(view.getContext(), imageView);
                    if (!matchIsActive) {
                        popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem item) {
                                switch (item.getItemId()) {
                                    case R.id.edit_match:

                                        /////////////////////////////////////////////////////////
                                        // Make this match the current one before sending the intent
                                        String matchId = hiddenMatchId.getText().toString();

                                        Intent intent = new Intent(itemView.getContext(), EditMatchActivity.class);
                                        intent.putExtra(EditMatchActivity.EXTRA_MATCH_ID, matchId);
                                        itemView.getContext().startActivity(intent);
                                        break;
                                    case R.id.delete_match:


                                        // to delete a match here
                                        // also remove from recyclerview

                                        break;
                                }
                                return false;
                            }
                        });
                    } else {

                        // If the current item is selected and you click on the side menu -> don't show delete
                        // delete isn't an option for active Matches
                        popup.getMenuInflater().inflate(R.menu.popup_menu_no_delete, popup.getMenu());
                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem item) {
                                switch (item.getItemId()) {
                                    case R.id.edit_match:
                                        // Make this match the current one before sending the intent


                                        Intent intent = new Intent(itemView.getContext(), EditMatchActivity.class);
                                        itemView.getContext().startActivity(intent);
                                        break;

                                }
                                return false;
                            }
                        });
                    }

                    //displaying the popup
                    popup.show();
                }
            });

            container.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    matchIsActive = true;   // maybe this is redundant

                    String matchName = tvName.getText().toString();
                    Gson gson = new Gson();

                    SharedPreferences.Editor editor = itemView.getContext().getSharedPreferences(
                            MY_GLOBAL_PREFS, itemView.getContext().MODE_PRIVATE).edit();
                    //editor.putString(CURRENT_MATCH_NAME, matchName);
                    editor.apply();


                    Intent intent = new Intent(itemView.getContext(), MainActivity.class);
                    itemView.getContext().startActivity(intent);

                }
            });

        }

    }
}

You can use tag to work with ids and indicies in order to store imageView.setTag(position);您可以使用 tag 来处理 ids 和 indicies 以存储imageView.setTag(position); in order to retrieve somewhere:为了检索某处:

@Override
public void onClick(View v) {
        int pos = (int) v.getTag();
        Match matches = mMatches.get(pos);

}

You should set onClickListener() in onBindViewHolder() method like this:您应该在 onBindViewHolder() 方法中设置 onClickListener() ,如下所示:

holder.imageView.setOnClickListener(...
Log.d("HEY, THIS IS CURRENT MATCH", mMatches.get(position));
...);

Is it clear?清楚吗?

as mentioned by pavel, inside of your onBindViewHolder() function is where you should set the listeners for your items.正如 pavel 所提到的,您应该在 onBindViewHolder() 函数内部为您的项目设置侦听器。

holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { .... } });

and

holder.container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { ... } });

one way is that you can first give an id of the list item layout for example you have chosen a linear layout then you should give an id and then initialize it inside the view holder class like private LinearLayout container = findViewBYiD(ID_YOU_HAVE CHOOSEN);一种方法是,您可以首先给出列表项布局的 id,例如您选择了线性布局,然后您应该给出一个 id,然后在视图持有者类中对其进行初始化,例如 private LinearLayout container = findViewBYiD(ID_YOU_HAVE CHOOSEN);

and then access it inside the OnBindViewHolder as: holder.container.setOnClickListener(CLICK_LISTENER);然后在 OnBindViewHolder 中访问它:holder.container.setOnClickListener(CLICK_LISTENER); inside the OnClick method you can access the object as: Match matches = mMatches.getItem(position);在 OnClick 方法中,您可以通过以下方式访问对象:匹配匹配 = mMatches.getItem(position);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM