Android 0 Basics Section 66th: Recyclerview Click event Handling

Source: Internet
Author: User

The previous two period learned the simple use of Recyclerview and added a split line to its item. In the actual use, whether it is a list or grid effect, the basic will be accompanied by a number of click Operations, then this issue to learn Recyclerview click events.

In the introduction of Recyclerview the beginning of a simple mention, to achieve some control click, long-pressure events need to complete their own, unlike the previous study of the ListView has its own clicklistener and Longclicklistener, but in fact more flexible and diverse, You can do it the way you want to click.

Still in the previous issue of the code base to modify, since Recyclerview does not provide the onclick and Onlongclick events, then we do it ourselves.

First, 2 interfaces Onitemclicklistener and Onitemlongclicklistener are defined in the Recyclerviewadapter class, and then 2 public methods are provided to facilitate activity settings for event monitoring. The listener event is set in the Onbindviewholder method, and when an event occurs, it can be recalled to the activity and then processed accordingly. The Recyclerviewadapter class modifies the following code:

 PackageCom.jinyu.cqkxzsxy.android.advancedviewsample.adapter;ImportAndroid.content.Context;ImportAndroid.support.v7.widget.RecyclerView;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.TextView;ImportCOM.JINYU.CQKXZSXY.ANDROID.ADVANCEDVIEWSAMPLE.R;Importjava.util.ArrayList;/*** @ Creator Xin 鱻 * @ description Android 0 Basic primer to Master Series Tutorial * Starting public number sharing talent Show (Shareexpert)*/ Public classRecyclerviewadapterextendsRecyclerview.adapter<recyclerviewadapter.viewholder> {    PrivateArraylist<string> Mdatas =NULL; PrivateLayoutinflater Minflater =NULL; PrivateOnitemclicklistener Monitemclicklistener =NULL; PrivateOnitemlongclicklistener Monitemlongclicklistener =NULL;  PublicRecyclerviewadapter (context context, arraylist<string>datas) {         This. Mdatas =datas;  This. Minflater =Layoutinflater.from (context); }    //Create a new view, called by LayoutManager@Override PublicViewholder Oncreateviewholder (viewgroup parent,intViewType) {View View= Minflater.inflate (R.layout.recyclerview_item, parent,false); Viewholder Vewholder=Newviewholder (view); returnVewholder; }    //actions to bind data to the interface@Override Public voidOnbindviewholder (FinalViewholder Holder,Final intposition) {String name=Mdatas.get (position); Holder.titleTv.setText ("Title" +name); Holder.contenTv.setText ("Content" +name); //Click event Registration and Distribution        if(NULL!=Monitemclicklistener) {Holder.titleTv.setOnClickListener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Monitemclicklistener.onclick (Holder.titletv, position);            }            }); Holder.contenTv.setOnClickListener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Monitemclicklistener.onclick (holder.contentv, position);        }            }); }        //long-press event registration and distribution        if(NULL!=Monitemlongclicklistener) {Holder.titleTv.setOnLongClickListener (NewView.onlongclicklistener () {@Override Public BooleanOnlongclick (View v) {returnMonitemlongclicklistener.onlongclick (Holder.titletv, position);            }            }); Holder.contenTv.setOnLongClickListener (NewView.onlongclicklistener () {@Override Public BooleanOnlongclick (View v) {returnMonitemlongclicklistener.onlongclick (HOLDER.CONTENTV, position);        }            }); }    }    //get the number of data@Override Public intGetItemCount () {returnMdatas = =NULL? 0: Mdatas.size (); }    //set up Click events     Public voidSetonitemclicklistener (Onitemclicklistener l) { This. Monitemclicklistener =l; }    //Set long Press events     Public voidSetonitemlongclicklistener (Onitemlongclicklistener l) { This. Monitemlongclicklistener =l; }    //Click event interface     Public InterfaceOnitemclicklistener {voidOnClick (View Parent,intposition); }    //long-press event interface     Public InterfaceOnitemlongclicklistener {BooleanOnlongclick (View Parent,intposition); }    //Custom Viewholder, holding all interface components for each item     Public classViewholderextendsRecyclerview.viewholder { PublicTextView Titletv =NULL;  PublicTextView Contentv =NULL;  PublicViewholder (View itemview) {Super(Itemview); Titletv=(TextView) Itemview.findviewbyid (R.ID.TITLE_TV); Contentv=(TextView) Itemview.findviewbyid (R.ID.CONTENT_TV); }    }}

This is followed by setting up listener events and responding to listener events in the activity, recyclerviewactivity the modified code as follows:

 Packagecom.jinyu.cqkxzsxy.android.advancedviewsample;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.support.v7.widget.DefaultItemAnimator;ImportAndroid.support.v7.widget.LinearLayoutManager;ImportAndroid.support.v7.widget.RecyclerView;ImportAndroid.view.View;ImportCom.jinyu.cqkxzsxy.android.advancedviewsample.adapter.RecyclerViewAdapter;ImportCom.jinyu.cqkxzsxy.android.advancedviewsample.view.RecyclerViewItemDivider;Importjava.util.ArrayList;/*** @ Creator Xin 鱻 * @ description Android 0 Basic primer to Master Series tutorials, welcome to the public number Shareexpert*/ Public classRecyclerviewactivityextendsAppcompatactivityImplementsRecyclerviewadapter.onitemclicklistener, Recyclerviewadapter.onitemlongclicklistener {PrivateRecyclerview Mrecyclerview =NULL; PrivateRecyclerviewadapter Madapter =NULL; PrivateArraylist<string> Mdatas =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.recyclerview_layout); //Get ComponentsMrecyclerview =(Recyclerview) Findviewbyid (R.id.recyclerview); //Settings ManagerLinearlayoutmanager LayoutManager =NewLinearlayoutmanager ( This);        Mrecyclerview.setlayoutmanager (LayoutManager); //Custom Split LineRecyclerview.itemdecoration itemdecoration =NewRecyclerviewitemdivider ( This, R.drawable.recyclerview_item_divider);        Mrecyclerview.additemdecoration (itemdecoration); //If you can determine the height of each item is fixed, set this option to raise the performanceMrecyclerview.sethasfixedsize (true); //initializing a list of dataInitdatas (); //setting up the adapterMadapter =NewRecyclerviewadapter ( This, Mdatas); Madapter.setonitemclicklistener ( This); Madapter.setonitemlongclicklistener ( This);    Mrecyclerview.setadapter (Madapter); }    Private voidInitdatas () {Mdatas=NewArraylist<>();  for(inti = 0; I < 50; i++) {Mdatas.add (I, I+ 1 + ""); }} @Override Public voidOnClick (View Parent,intposition) {Toast.maketext ( This, "clicked" + (position + 1) + "item", Toast.length_short). Show (); } @Override Public BooleanOnlongclick (View Parent,intposition) {Toast.maketext ( This, "Long pressed the first" + (position + 1) + "item", Toast.length_short). Show (); return true; }}

The rest of the layout file code does not change, rerun the program, and then you can test the click event and the long-voltage event, the effect is as follows:

This is a simple way to listen to the 2 TextView views in item, and if you need the whole item to do event handling, or one of them, and the same principle as the case above, you can practice it yourself.

Come here today, if you have any questions welcome message to discuss together, also welcome to join the Android 0 Basic introductory Technical discussion group, grow together!

This article copyright for the public Share talent show (Shareexpert)--Xin 鱻 all, if necessary reprint please contact the author authorized, hereby declare!

Past period Summary share:

Android 0 Basics Introduction 1th: Android's past life

Android 0 Basics Section 2nd: Android system Architecture and application components those things

Android 0 Basics Section 3rd: Bring you up to talk about Android development environment

Android 0 Basics 4th: Installing and configuring the JDK correctly Ko fu the first trick

Android 0 Basics 5th: Use ADT bundles to easily meet the goddess

Android 0 Basics 6th: Configuration Optimization SDK Manager, official dating goddess

Android 0 Basics 7th: Take care of Android simulator and start the Sweet journey

Android 0 Basics 8th: HelloWorld, the starting point for my first trip

Android 0 Basics 9th: Android app, no code can be developed

Android 0 Basics Section 10th: Development IDE Big upgrade, finally ushered in Android Studio

Android 0 Basics Introductory Section 11th: Simple steps to take you to fly, run Android Studio project

Android 0 Basics 12th: Get familiar with the Android studio interface and start selling

Android 0 Basics 13th: Android Studio Personalized configuration to create a tool for development

Android 0 Basics 14th: Using high-speed genymotion, stepping into the rocket era

Android 0 Basics Section 15th: Mastering the Android Studio project structure, sailing

Android 0 Basics Section 16th: Android User Interface Development overview

Android 0 Basics Section 17th: text box TextView

Android 0 Basics Section 18th: Input box EditText

Android 0 Basics Get started section 19th: Buttons button

Android 0 Basics 20th: check box checkbox and radio button radiobutton

Android 0 Basics Section 21st: Switch Components ToggleButton and switch

Android 0 Basics Section 22nd: Image View ImageView

Android 0 Basics Section 23rd: Image button ImageButton and zoom button Zoombutton

Android 0 Basics Section 24th: Customize view simple to use to create your own controls

Android 0 Basics Section 25th: Simple and most commonly used linearlayout linear layouts

Android 0 Basics Section 26th: Two alignments, layout_gravity and gravity differ greatly

Android 0 Basics section 27th: Using padding and margin correctly

Android 0 Basics Section 28th: Easy to master relativelayout relative layout

Android 0 Basics 29th: Use tablelayout table layouts

Android 0 Basics 30th: Two minutes master Framelayout frame layout

Android 0 Basics Section 31st: absolutelayout absolute Layout with less

Android 0 Basics Section 32nd: New GridLayout Grid layout

Android 0 Basics section 33rd: Android Event Handling overview

Android 0 Basics Section 34th: Listening-based event handling in Android

Android 0 Basics Section 35th: Callback-based event handling in Android

Android 0 Basics Section 36th: Handling of Android system events

Android 0 Basics 37th: First Knowledge ListView

Android 0 Basics 38th: First Knowledge Adapter

Android 0 Basics section 39th: listactivity and custom list items

Android 0 Basics Section 40th: Customizing Arrayadapter

Android 0 Basics Section 41st: Using Simpleadapter

Android 0 Basics Section 42nd: Customizing Baseadapter

Android 0 Basics section 43rd: ListView Optimization and List End-to-end use

Android 0 Basics Section 44th: ListView Data Dynamic Update

Android 0 Basic Getting Started section 45th: Grid view GridView

Android 0 Basics section 46th: List Options Box spinner

Android 0 Basic Getting Started section 47th: AutoComplete text Box Autocompletetextview

Android 0 Basics Section 48th: Collapsible list Expandablelistview

Android 0 Basics section 49th: Adapterviewflipper picture Carousel

Android 0 Basics Section 50th: StackView card Stacking

Android 0 Basics Section 51st: progress bar ProgressBar

Android 0 Basics section 52nd: Customizing ProgressBar Cool progress bar

Android 0 Basics 53rd: Drag bar Seekbar and star rating bar Ratingbar

Android 0 Basics section 54th: View switch Components Viewswitcher

Android 0 Basics Section 55th: Imageswitcher and Textswitcher

Android 0 Basics Section 56th: Flip View Viewflipper

Android 0 Basics Section 57th: DatePicker and Timepicker selectors

Android 0 Basics Section 58th: Value selector numberpicker

Android 0 Basics Section 59th: Common Three clock clocks components

Android 0 Basics Section 60th: Calendar view CalendarView and timer chronometer

Android 0 Basics Section 61st: Scrolling view ScrollView

Android 0 Basics section 62nd: Search box Component Searchview

Android 0 Basics Introductory Section 63rd: Learn from the tab tabhost

Android 0 Basics 64th: Uncover Recyclerview

Android 0 Basics Section 65th: Recyclerview Split Line Development tips

Android 0 Basics Section 66th: Recyclerview Click event Handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.