Introductory tutorials for Recyclerview components in Android application development _android

Source: Internet
Author: User
Tags documentation


Recyclerview is a list container that has been published for a long time before remembering what to write.



Compared to ListView, Recyclerview is more flexible when reusing reuse, which is low coupling and provides an extension. When loading multiple views, you should use Recyclerview instead of ListView.



So let's take a look at how this thing should work. For example, a view that generates a waterfall stream.






First we start with a HelloWorld and see how to build a recyclerview.



1. Dependent libraries
gradle configuration, add recycler Library


Compile ' com.android.support:recyclerview-v7:+ '


2. Resource Documents
resource File


 <android.support.v7.widget.recyclerview
  android:id= "@+id/test_recycler_view"
  android:layout_width= " Match_parent "
  android:layout_height=" Match_parent "/>

3. Code
LayoutManager: Manage the Recyclerview structure.
Adapter: Handles the display of each item.
Itemdecoration: Add decoration for each item.
Itemanimator: Animation effect when adding \ remove \ reorder.
Layoutmanager\adapter is a must, Itemdecoration\itemanimator is optional.
 /**
  * Initialize recyclerview
  *
  * @param recyclerview main control
 /private void Initrecyclerview (Recyclerview Recyclerview) {
  recyclerview.sethasfixedsize (true);//Set Fixed size
  Initrecyclerlayoutmanager (Recyclerview); Initialize layout
  initrecycleradapter (recyclerview);//Initialize Adapter
  inititemdecoration (Recyclerview);//Initialize decoration
  Inititemanimator (Recyclerview); Initialize animation effects
 }


4. LayoutManager
manage the Recyclerview layout structure.


 private void Initrecyclerlayoutmanager (Recyclerview recyclerview) {
  //Wrong column grid layout
  Recyclerview.setlayoutmanager (New Staggeredgridlayoutmanager (4,
    staggeredgridlayoutmanager.vertical));
 }


Provides a variety of layoutmanager, waterfall flow using the wrong column grid layout.
5. Adapter
adapter that handles the Recyclerview item transaction.


 private void Initrecycleradapter (Recyclerview recyclerview) {
  madapter = new Myadapter (GetData ());
  Recyclerview.setadapter (Madapter);
 }


For adapter, we need to start by looking at the class.


Public class MyAdapter extends extends clerview. Adapter<myviewholder> {</myviewholder>

Private List < DataModel > mDataModels;
Private List < Integer > mHeights;

MyAdapter (List < DataModel > dataModels) {
If (dataModels == null) {
Throw new IllegalArgumentException("DataModel must not be null");
}
MDataModels = dataModels;
MHeights = new ArrayList < > ();
}

@ Override
Public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
The View itemView = LayoutInflater. The from (parent. GetContext ())
Inflate (R.l ayout item_recycler_view, parent, false);
Return new MyViewHolder (itemView);
}

@ Override
Public void onBindViewHolder(MyViewHolder holder, int position) {
DataModel DataModel = mDataModels. Get (position);

// random height, simulate waterfall effect.
If (mHeights. Size () <= position) {
MHeights. Add ((int) (100 + math.random () * 300));
}

ViewGroup. LayoutParams lp = holder. GetTvLabel () getLayoutParams ();
Lp. Height = mHeights. Get (position);

Holder. GetTvLabel (.) setLayoutParams (lp);

Holder. GetTvLabel (.) setText (dataModel. GetLabel ());
Holder. GetTvDateTime (.) setText (new SimpleDateFormat (" yyyy - MM - dd ", Locale. ENGLISH)
. The format (dataModel. GetDateTime ()));
}

@ Override
Public int getItemCount () {
Return mDataModels. The size ();
}

Public void addData(int position) {
DataModel model = new DataModel();
Model. SetDateTime (getBeforeDay (new Date (), the position));
Model.setlabel ("No. "+ (int) (new Random().nextdouble () * 20.0f));

MDataModels. Add (position, model);
NotifyItemInserted (position);
}

Public void removeData(int position) {
MDataModels. Remove (position);
NotifyItemRemoved (position);
}

/ * *
* the day before the date of acquisition
*
* @param date date
* @param I deviation
* @return a new date
* /
Private static Date getBeforeDay(Date Date, int I) {
Calendar Calendar = Calendar. GetInstance ();
Calendar. SetTime (date);
Calendar. The add (calendar. DAY_OF_YEAR, I * (1));
Return to the calendar. GetTime ();
}
}

(1) Oncreateviewholder create Viewholder.



(2) Onbindviewholder bind each item of data.



(3) GetItemCount returns the length of the list.



(4) Recyclerview enforces the use of viewholder.


public class Myviewholder extends Recyclerview.viewholder {

 private TextView Mtvlabel;//label
 private TextView MTv DateTime; Date public

 Myviewholder (View itemview) {
  super (Itemview);
  Mtvlabel = (TextView) Itemview.findviewbyid (r.id.item_text);
  Mtvdatetime = (TextView) Itemview.findviewbyid (r.id.item_date);
 }

 Public TextView Gettvlabel () {return
  mtvlabel;
 }

 Public TextView Gettvdatetime () {return
  mtvdatetime;
 }

}


In the Oncreateviewholder method, create the class; In the Onbindviewholder method, bind the data.
Datamodel


public class Datamodel {

 private String Mlabel;
 Private Date mdatetime;

 Public String Getlabel () {return
  mlabel;
 }

 public void SetLabel (String label) {
  mlabel = label;
 }

 Public Date GetDateTime () {return
  mdatetime;
 }

 public void SetDateTime (Date dateTime) {
  mdatetime = dateTime;
 }
}


6. Itemdecoration
items, such as ListView in the line, in this case, left and right two pink.


 private void Inititemdecoration (Recyclerview recyclerview) {
  recyclerview.additemdecoration (new Myitemdecoration (this));
 


Itemdecoration, notice how the parent and child are used.


Public class MyItemDecoration extends RecyclerView. ItemDecoration {

Private static final int [] ATTRS = new int [] {android. State Richard armitage TTR event. ListDivider};
Private Drawable mDivider;

Public MyItemDecoration Context (Context) {
Final TypedArray array = context. ObtainStyledAttributes (ATTRS);
MDivider = array. GetDrawable (0);
Array. Recycle ();
}

@ Override
Public void onDraw(Canvas c, RecyclerView parent, State) {
DrawHorizontal (c, parent);
DrawVertical (c, parent);
}

/ / horizontal line
Public void drawHorizontal(Canvas c, RecyclerView parent) {

Final int childCount = parent.getchildcount ();

// draw a line at the bottom of each child control
For (int I = 0; I < childCount; I++) {
Final View child = parent.getchildat (I);

Final int left = child.getleft () + child.getpaddingleft ();
Final int right = child.getwidth () + child.getleft () -child.getpaddingright ();
Final int top = child. GetBottom () - mDivider. GetIntrinsicHeight () - child. GetPaddingBottom ();
Final int bottom = top + mDivider. GetIntrinsicHeight ();
MDivider. SetBounds (left, top, right, bottom);
MDivider. The draw (c);
}
}

/ / vertical line
Public void drawVertical(Canvas c, RecyclerView parent) {

Final int childCount = parent.getchildcount ();

// draw a line to the right of each child control
For (int I = 0; I < childCount; I++) {
Final View child = parent.getchildat (I);
Int right = child.getright () - child.getpaddingright ();
Int left = right - mDivider. GetIntrinsicWidth ();
Final int top = child.gettop () + child.getpaddingtop ();
Final int bottom = child.gettop () + child.getheight () - child.getpaddingbottom ();

MDivider. SetBounds (left, top, right, bottom);
MDivider. The draw (c);
}
}

// white space between items
@ Override
Public void getItemOffsets(Rect outRect, View View, RecyclerView parent, State) {
OutRect. Set (0, 0, mDivider getIntrinsicWidth (), mDivider. GetIntrinsicHeight ());
}
}


This example overrides the Listdivider


 <style name= "Apptheme" parent= "Theme.AppCompat.Light.DarkActionBar" > ...
  <item name= "Android:listdivider" > @drawable/divider_bg</item>
 </style>
<?xml version = "1.0" encoding= "Utf-8"?>
<shape xmlns:android= "Http://schemas.android.com/apk/res/android"
  Android:shape= "Rectangle" >
 <solid android:color= "#ff00ff"/> <size android:height=
 "4DP"/>
 <size android:width= "4DP"/>
</shape>


7. Itemanimator
The animation is more complex and uses the default animation. If you want to customize the words, inherit defaultitemanimator; If you set NULL, no animations are displayed.


 private void Inititemanimator (Recyclerview recyclerview) {
  recyclerview.setitemanimator (new Defaultitemanimator ()); Default Animation
 }


8. Final activity


Public class MainActivity extends AppCompatActivity {

Private MyAdapter mAdapter;

@ Override
Protected void onCreate(Bundle savedInstanceState) {
Super. OnCreate (savedInstanceState);
The setContentView (R.l ayout. Activity_main);
Toolbar = (Toolbar) findViewById(r.d.toolbar);
SetSupportActionBar (toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(r.id.fab);
Fab. SetOnClickListener (new View. An OnClickListener () {
@ Override
Public void onClick(View View) {
Make (view, "Replace with your own action", snackbar.length_long)
SetAction (" Action ", null). The show ();
}
});

// initialize RecyclerView
InitRecyclerView ((RecyclerView) the findViewById (R.i which est_recycler_view));
}

/ * *
* initialize RecyclerView
*
* @param recyclerView master
* /
Private void initRecyclerView(RecyclerView RecyclerView) {
RecyclerView. SetHasFixedSize (true); // set a fixed size
InitRecyclerLayoutManager (recyclerView); // initializes LayoutManager
InitRecyclerAdapter (recyclerView); // initialize the Adapter
InitItemDecoration (recyclerView); // initializes border decorations
InitItemAnimator (recyclerView); // initializes the animation effect
}

/ * *
* initialize the LayoutManager of RecyclerView
*
* @param recyclerView master
* /
Private void initRecyclerLayoutManager (RecyclerView RecyclerView) {
// wrong column grid layout
RecyclerView. SetLayoutManager (new StaggeredGridLayoutManager (4,
StaggeredGridLayoutManager. VERTICAL));
}

/ * *
* initialize the Adapter of RecyclerView
*
* @param recyclerView master
* /
Private void initRecyclerAdapter(RecyclerView RecyclerView) {
MAdapter = new MyAdapter (getData ());
RecyclerView. SetAdapter (mAdapter);
}

/ * *
* initializes the ItemDecoration of RecyclerView
*
* @param recyclerView master
* /
Private void initItemDecoration(RecyclerView RecyclerView) {
RecyclerView. AddItemDecoration (new MyItemDecoration (this));
}

/ * *
* initializes the (ItemAnimator) item animation of RecyclerView
*
* @param recyclerView master
* /
Private void initItemAnimator(RecyclerView RecyclerView) {
RecyclerView. SetItemAnimator (new DefaultItemAnimator ()); // default animation
}

/ * *
* simulated data
*
* @ return data
* /
Private ArrayList < DataModel > getData () {
Int count = 57;
ArrayList<datamodel> data = new ArrayList<>();</datamodel>
For (int I = 0; I < count; I++) {
DataModel model = new DataModel();

Model. SetDateTime (getBeforeDay (new Date (), I));
Model. SetLabel (" No. "+ I);

Data. The add (model);
}

Return the data.
}

/ * *
* the day before the date of acquisition
*
* @param date date
* @param I deviation
* @return a new date
* /
Private static Date getBeforeDay(Date Date, int I) {
Calendar Calendar = Calendar. GetInstance ();
Calendar. SetTime (date);
Calendar. The add (calendar. DAY_OF_YEAR, I * (1));
Return to the calendar. GetTime ();
}


@ Override
Public Boolean onCreateOptionsMenu(Menu Menu) {
/ / to Inflate the menu; This adds items to the action bar if it is present.
GetMenuInflater (). Inflate (R.m emu. Menu_main, menu).
Return true;
}

@ Override
Public Boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in androidmanifest.xml
Int id = item. GetItemId ();

The switch (item. GetItemId ()) {
Case R.i d.i d_action_add:
MAdapter. AddData (1);
Break;
Case R.i d.i d_action_delete:
MAdapter. RemoveData (1);
Break;
}

/ / noinspection SimplifiableIfStatement
If (id == R.D.A ction_settings) {
Return true;

}

Return super. OnOptionsItemSelected (item);
}
} 


To test the animation, the menu adds two additional buttons.



9. Run Reactnative Sample
since the feeling reactnative development is reliable, then we come to see what reactnative can do what fun things, and native of what is the difference?
Sample diagram









Follow the documentation to install some command-line tools, and then download the GIT code.
Github:https://github.com/facebook/react-native



A lot of content, including some dependent libraries and samples (Example), download a bit slow, patiently waiting.



After the download is complete, perform NPM install within the react-native.



Android project execution, refer to Reactandroid's readme.md.



In the React-native directory, create a new local.properties


SDK.DIR=/USERS/WANGCHENLONG/INSTALLATIONS/ANDROID-SDK
ndk.dir=/users/wangchenlong/installations/ android-ndk-r10e


Perform


CD react-native
./gradlew:reactandroid:assembledebug


Re-execution


./gradlew:reactandroid:installarchives


Start a service


./packager/packager.sh


Installation Project


CD react-native
./gradlew:examples:uiexplorer:android:app:installdebug


Be sure to start the service first and then install the project.
Transforming 100% appears, the import is successful.






In the latest version, my red M note4 cannot run the project.
Error: Upload package to device fails.
The reason is that the compiled Gradle version is too high, the default 1.5.0, the actual 1.2.0~1.3.0 can run.
Mine is 1.2.3.
True machine debugging, I red M note (Android 4.2)
Shake the phone and select Dev Settings->debug Sever host & port for device. Set IP address, observe the IP of this machine, fill in can. My current is



192.168.2.202:8081
Note Set port 8081, otherwise it cannot be loaded. In some cases, you can enter IP directly.
Android5.0 above, set the port directly.


ADB reverse tcp:8081 tcp:8081


Refer to Android's true machine Debug documentation.



iOS simulator, too poor without an iphone. Open the Open Uiexplorer.xcodeproj project directly, execution can be displayed.



Development has two options, one is directly based on reactnative development, one is to integrate Reactnative into the existing app, for the second, we need to focus on, reactnative will increase the number of code?



Using the most basic HelloWorld to do the test, reactnative is also to generate a simple HelloWorld js. The latest generation of HelloWorld size is 1.4M, plus reactnative is 7.6M, frame about 6.2M, you can weigh the use.



Reactnative's uiexplorer already contains a large number of examples, very close to the original, very gorgeous and fast. Like Android's Viewpager






OK, good start is half the success, continue to explore it! Enjoy it!


Related Article

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.