如何在OnClickListener中检索RecyclerView中的索引/位置?

时间:2018-08-14 13:35:37

标签: android android-recyclerview

我对使用RecyclerView并不陌生,我试图检索每个项目的索引,以便可以将其与Recipe对象一起传递给片段,然后从Recipe对象中检索特定于索引的数据。有没有简单的方法可以解决这个问题?配方对象中有一个数据列表,该数据列表与单击的视图相对应。

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);
            }
        }
    }
}

4 个答案:

答案 0 :(得分:1)

您只需在onBindViewHolder方法中添加侦听器:

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
         }
    }
}

此外,您可以将所需的信息设置为视图标记(与holder.itemView.setTag(mValue)相同,但是不能定位而不是mValue)并在侦听器中检索到它

答案 1 :(得分:1)

您正在标记中设置整个列表,而不是只能设置位置。

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

然后从该视图中检索位置。

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

您已经将Recipe对象创建为全局变量。因此,您可以在侦听器中使用该对象。

答案 2 :(得分:1)

像这样设置标签:

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

在您的onClick内:

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

答案 3 :(得分:0)

在onclick中使用方法getAdapterPosition(),以获取recyclerview中的当前点击位置。