Skip to content Skip to sidebar Skip to footer

Recyclerview Single Item Id

Ehi, i'm modding an example app i found on the Internet. (learn2crack) I want to get the ID of a single row in my ReclycerView. Here's the code. Main private void initViews(){

Solution 1:

Don't use the OnTouch event on the RecyclerView itself.

Set up an OnClick on the view in onBindViewHolder. When it is fired, call back to the Activity with the row of the touched item.

Create the adapter with the interface

    MyAdapter adp=newMyAdapter(newMyAdapter.InterfaceCommands() {
        @OverridepublicvoidOnItemPressed(int position) {
            // do something
        }
    });

Incomplete Example Adapter.

publicclassMyAdapterextendsRecyclerView.Adapter<MyAdapter.VH> {

    publicMyAdapter(InterfaceCommands i) {
        MyCommands = i;
    }

    publicinterfaceInterfaceCommands {

        publicvoidOnItemPressed(int position);

    }

    private InterfaceCommands MyCommands;

    @OverridepublicvoidonBindViewHolder(final MyAdapter.VH holder, finalint position) {

        // Set Up ViewHolder pattern// ....

        holder.containerView.setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View view) {

                intposition= holder.getAdapterPosition();

                MyCommands.OnItemPressed(position);

            }
        });

    }

}

Solution 2:

Create an interface called ItemClickListener

publicinterfaceItemClickListener {
    voidonClick(int position);
}

Implement this interface in your activity, and keep a reference of adapter input

private ArrayList<AndroidVersion> android_version;

....
....

@OverridepublicvoidonClick(int position) {
    AndroidVersionversion= android_version.get(position);
    // do your task with retrieved AndroidVersion
}

Change the adapter constructor like below

new DataAdapter(getApplicationContext(),androidVersions, itemClickListener);

Inside the DataAdapter class

viewHolder.tv_android.setOnClickListener(newView.OnClickListener() {

        @OverridepublicvoidonClick(View argi) {
            //Toast.makeText(context,String.valueOf(i),Toast.LENGTH_SHORT).show();if(itemClickListener != null) {
                itemClickListener.onClick(i);
            }
        }
    });

Post a Comment for "Recyclerview Single Item Id"