J.J.
J.J.

Reputation: 1118

How can view index/position within RecyclerView be retrieved within OnClickListener?

I am new to working with RecyclerView and I am attempting to retrieve each item's index so that I can pass it to a fragment with the Recipe object, and then retrieve index-spexific data from the Recipe object. Is there a simple way to go about this? There is a list of data within the recipe object that will correspond to the view on which is clicked.

public class ItemListActivity extends AppCompatActivity {

    public static final String EXTRA_POSITION = "extra_position";
    private static final int DEFAULT_POSITION = -1;
    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

    Recipe r = new Recipe();
    public void setRecipe(Recipe recipe){
        this.r = recipe;
    }

    public Recipe getRecipe(){
        return r;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_list);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle(getTitle());


        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-w900dp).
            // If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;
        }

        View recyclerView = findViewById(R.id.item_list);
        assert recyclerView != null;
        setupRecyclerView((RecyclerView) recyclerView);
    }

    private void setupRecyclerView(@NonNull RecyclerView recyclerView) {

        Recipe r;
        try {
            MyParcelable myParcelable = (MyParcelable) getIntent().getExtras().getParcelable("MyParcelable");
            Object myObject = myParcelable.getObject();
            r = (Recipe) myObject;
        }
        catch(Exception ex){

        }

        recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(this, r, mTwoPane));
    }

    public static class SimpleItemRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {

        private final ItemListActivity mParentActivity;
        private final Recipe mValue;
        private final boolean mTwoPane;
        private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Recipe item = (Recipe) view.getTag();
                //want to get item indexes here to pass along to fragment, so that I can retrieve index-specific data from Recipe object

                if (mTwoPane) {
                    Bundle arguments = new Bundle();
                    arguments.putString(ItemDetailFragment.ARG_ITEM_ID, item.stepsList.get(0).shortDescription);
                    ItemDetailFragment fragment = new ItemDetailFragment();
                    fragment.setArguments(arguments);
                    fragment.setRecipe(mValue);
                    mParentActivity.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.item_detail_container, fragment)
                            .commit();
                } else {
                    Context context = view.getContext();
                    Intent intent = new Intent(context, ItemDetailActivity.class);
                    intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, item.stepsList.get(0).shortDescription);

                    context.startActivity(intent);
                }
            }
        };

        SimpleItemRecyclerViewAdapter(ItemListActivity parent,
                                      Recipe item,
                                      boolean twoPane) {
            mValue = item;
            mParentActivity = parent;
            mTwoPane = twoPane;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_list_content, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            String ingredients = "";

            for (int i = 0; i < mValue.ingredientList.size(); i++){
                ingredients += mValue.ingredientList.get(i).ingredientName + "\n";
            }

            if (position > 0) {
                holder.mIdView.setText(mValue.stepsList.get(position-1).shortDescription);
                holder.mContentView.setText(mValue.stepsList.get(position-1).description);

                holder.itemView.setTag(mValue);
                holder.itemView.setOnClickListener(mOnClickListener);
            }
            else{
                holder.mIdView.setText(ingredients);
                holder.mContentView.setText("");

                holder.itemView.setTag(mValue);
                holder.itemView.setOnClickListener(mOnClickListener);
            }
        }

        @Override
        public int getItemCount() {
            return (mValue.stepsList.size() + 1);
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            final TextView mIdView;
            final TextView mContentView;

            ViewHolder(View view) {
                super(view);
                mIdView = (TextView) view.findViewById(R.id.id_text);
                mContentView = (TextView) view.findViewById(R.id.content);
            }
        }
    }
}

Upvotes: 0

Views: 71

Answers (4)

prashant17
prashant17

Reputation: 1550

Set Tag like this:

holder.itemView.setTag(R.string.model,mValue);
holder.itemView.setTag(R.string.position,position);

Inside your onClick:

Recipe item = (Recipe) view.getTag(R.string.model);
int pos = (int) view.getTag(R.string.position);

Upvotes: 1

Mahavir Jain
Mahavir Jain

Reputation: 1561

You are setting the whole list in the tag instead of that you can set the position only .

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
         holder.itemView.setTag(position);
         holder.itemView.setOnClickListener(mOnClickListener);
        }

And retrieve the position from that view.

 private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            int position = (int) view.getTag();  
 }

You already created the Recipe object as global variable . So you can use that object inside the listener.

Upvotes: 1

H.Taras
H.Taras

Reputation: 832

You can simply add listener in your onBindViewHolder method:

public void onBindViewHolder(final ViewHolder holder, int position) {
    //some logic
    view.setOnClickListener(new OnClickListener() { 
         onClick(View view) {
             //here you have access to your object and position
         }
    }
}

Also, you can set needed info as view tag (the same way you did holder.itemView.setTag(mValue), but not position instead of mValue) and retrieve it in your listener

Upvotes: 1

gautam
gautam

Reputation: 1851

Use method getAdapterPosition() inside onclick to get the current click position in recyclerview.

Upvotes: 0

Related Questions