Android Recyclerview Layout replaces the GridView to implement a Alipay-like interface _android

Source: Internet
Author: User

Using the GridView alone
two common methods for adding a split line to the GridView; http://stackoverflow.com/questions/7132030/android-gridview-draw-dividers
Add a split line to the GridView, that is, to achieve the grid layout, it is not clear why Google did not add a similar ListView to the GridView divider attribute, so we need to add a split line,
At present two methods, the first one is the use of the GridView android:horizontalspacing= "1DP" and android:verticalspacing= "1DP" attributes to use the background color of the GridView With the Itemview background color, the gap between the lines as a dividing line.
The split line effect diagram using the Spacing attribute:

This method can realize the mesh dividing line, but the disadvantage is that the item does not have the place, its display is the background color, not very beautiful.
This is our reference Alipay: Alipay do is, the default is the whole line, not enough positive line, add Blank item.
As shown in figure:

Not also put an item placeholder, you can solve the background problem.

The second method is to use the background selector Selector.
Comparing the first method, the second method is simpler, but there is also a small flaw, because item uses selector, then the split line between adjacent two item equals two, and deepens.
As shown in the figure:

Carefully look at the picture, online recharge the right side of the line, compared to the above line is not obvious.

Recyclerview
Let's start with today's main character. Put aside the top of the carousel diagram does not say, the following table the first thing you can think of is the GridView. However, now that we have a new and powerful Recyclerview control, we can discard the ListView or the GridView in most scenarios. And for Recyclerview alternative ListView, I believe we have a certain understanding and in the project has a certain application, but for the Recyclerview alternative to the use of the GridView, may be a little unfamiliar. Next, in this article, we will elaborate on how to use the Recyclerview a control, to handle such a home page.

Integrated Recyclerview

First of all, if you have never tried Recyclerview, of course you have to make the following configuration in Build.gradle to integrate Recyclerview

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

Layout

Now we are in mainactivity simple to achieve the effect we want, then in Activity_main.xml as long as there is a recyclerview can be. As follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
  xmlns:tools= "http:// Schemas.android.com/tools "
  android:layout_width=" match_parent "
  android:layout_height=" Match_parent "
  tools:context= ". Mainactivity ">

  <android.support.v7.widget.recyclerview
    android:id=" @+id/home_rv "
    android: Layout_width= "Match_parent"
    android:layout_height= "match_parent"/>

</RelativeLayout>

Adapter

First, let's take a look at how adapter was written.

public class Myadapter extends Recyclerview.adapter {//First define two itemviewtype,0 representative headers, 1 represents the middle part of the table private static final int IT
  Em_view_type_header = 0;
  private static final int item_view_type_item = 1;

  Data source private list<string> dataList;
  Constructor public Myadapter (List<string> dataList) {this.datalist = dataList; /** * To determine whether the current position is in the first * @param position * @return * * public boolean isheader (int position) {RE
  Turn position = = 0; @Override public Recyclerview.viewholder Oncreateviewholder (viewgroup viewgroup, int viewtype) {//in Oncreatevie In the Wholder method, we have to return different viewholder if (ViewType = = Item_view_type_header) {//For header, we should return the fill with header pair according to different viewtype. The layout file should be Viewholder (again we are returning a layout file, please make the corresponding changes according to different requirements) return to the new Headerviewholder (Layoutinflater.from (
    Viewgroup.getcontext ()). Inflate (R.layout.layout_item, null)); else {//for item in body, we also return the corresponding Viewholder returns new Bodyviewholder (VieWgroup.getcontext ()). Inflate (R.layout.layout_item, null)); @Override public void Onbindviewholder (Recyclerview.viewholder viewholder, int position) {if IsHeader (pos  ition)) {//Everyone is dealing with the head here, there is only one textview, you can make changes according to your own logic ((Headerviewholder) viewholder). Gettextview (). SetText ("This is the header!! ");}
    else {//other entries in the logic in this ((Bodyviewholder) viewholder). Gettextview (). SetText (Datalist.get (position-1)); }/** * Total number of entries is the number of data sources +1, because we have a header * @return * * * @Override public int getitemcount () {return datal
  Ist.size () + 1; /** * * Multiplexing Getitemviewtype method, returning corresponding ViewType * @param position * @return/@Override public int according to position Getitemviewtype (int position) {//If 0, is the head, otherwise is the other item return IsHeader (position)?
  Item_view_type_header:item_view_type_item; /** * to the head of the special Viewholder, everyone according to the needs of their own modification * * public class Headerviewholder extends Recyclerview.viewholder {priv
    Ate TextView TextView; PuBlic Headerviewholder (View itemview) {super (Itemview);
    TextView = (TextView) Itemview.findviewbyid (R.ID.ITEM_TV);
    Public TextView Gettextview () {return TextView; }/** * to the Viewholder in the GridView, there is only one TextView/public class Bodyviewholder extends recyclerview.viewho
    Lder {private TextView TextView;
      Public Bodyviewholder (View Itemview) {super (Itemview);
    TextView = (TextView) Itemview.findviewbyid (R.ID.ITEM_TV);
    Public TextView Gettextview () {return TextView;

 }
  }
}

Item Layout File:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
  android:layout_width= "Match_ Parent "
  android:layout_height=" wrap_content "
  android:orientation=" vertical ">

  <textview
    Android:id= "@+id/item_tv"
    android:layout_width= "match_parent"
    android:layout_height= "100DP"
    android:gravity= "center"/>

</RelativeLayout>

Activity

Next, let's look at how our code in the activity is written.

public class Mainactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {Supe
    R.oncreate (savedinstancestate);

    Setcontentview (R.layout.activity_main);

    Locate the Recyclerview control Recyclerview HOME_RV = (recyclerview) Findviewbyid (R.ID.HOME_RV);
    Do some fake data list<string> dataList = new arraylist<> ();
    Datalist.add ("first");
    Datalist.add ("second");
    Datalist.add ("third");
    Datalist.add ("Fourth");
    Datalist.add ("fifth");
    Datalist.add ("sixth");
    Datalist.add ("Seventh");
    Datalist.add ("eighth");

    Datalist.add ("Nineth");
    Instantiate the adapter and set the final myadapter adapter = new Myadapter (dataList) to Recyclerview;

    Home_rv.setadapter (adapter); If we want a recyclerview of the GridView form, then on LayoutManager we will use Gridlayoutmanager//Instantiate a Gridlayoutmanager, the number of columns is 3 final G

    Ridlayoutmanager LayoutManager = new Gridlayoutmanager (this, 3); Call the following method so that the first entry for Recyclerview is only a 1-column layoutmanager.setspansizelookup (new Gridlayoutmanager.Spansizelookup () {@Override public int getspansize (int position) {//If position is 0, then this entry will occupy Spancount () so many columns Number, then this is 3//And if not 0, then the description is not header, Occupy 1 columns can return Adapter.isheader (position)?
      Layoutmanager.getspancount (): 1;

    }
    });
  Setting the LayoutManager to Recyclerview Home_rv.setlayoutmanager (LayoutManager);

 }
}

OK, then let's run a look at the effect!

Well, then there is a little gap with the effect chart, is to draw a line!
How should I draw the line? Draw in a layout file? Seemingly feasible, but what if the borders of each entry are irregular? Do you want to draw a bunch of layout files? It's too much trouble.
So the recyclerview that will be used here are another big feature: Itemdecoration.

Here we write a class called Myitemdecoration, as follows:

public class Myitemdecoration extends Recyclerview.itemdecoration {/** * replication OnDraw method so that before each entry is drawn (or after), let him draw it for us first.  A few lines. * @param c * @param parent * @param state/@Override public void OnDraw (Canvas C, Recyclerview
    Parent, Recyclerview.state State) {//First initialize a paint to simply specify the color of canvas, it's black!
    Paint Paint = new Paint (); Paint.setcolor (Parent.getcontext (). Getresources (). GetColor (Android.

    R.color.black));

    Get the total number of entries in Recyclerview int childcount = Parent.getchildcount ();
      Iterate over for (int i = 0; i < ChildCount i++) {if (i = = 0) {//If the first entry, then we do not draw a border of the continue;

      //Get the view of the child view, which is the item, ready to draw him a border view Childview = Parent.getchildat (i);
      First get the width of the child view, as well as the position on the screen, convenient for us to get the specific coordinates of the border float x = Childview.getx ();
      Float y = childview.gety ();
      int width = childview.getwidth ();

      int height = childview.getheight ();
      The line c.drawline (x, y, x + width, y, paint) of the surrounding lines of the entries according to these dots; C. drawLine (x, y, x, y + height, paint);
      C.drawline (x + width, y, x + width, y + height, paint);

      C.drawline (x, y + height, x + width, y + height, paint);
  Of course, here we must be based on their own different design drafts to draw lines, or draw some other things, can be done here, very convenient} Super.ondraw (c, parent, state);

 }
}

Back to our activity, add the following code:

Set our custom itemdecoration to Recyclerview
home_rv.additemdecoration (New Myitemdecoration ());

Finally, see what the effect is:

Of course, although there are some flaws in the final effect, but I believe that everyone has a basic understanding of the idea, the application of their own projects in the time must also make corresponding adjustments.

Finally, we have to say that now Recyclerview has basically the ability to replace the ListView and the GridView, in our project knowledge, most of the lists are already in the form of Recyclerview control as the display. This article is only from a very entry-level point of view to explain how to use Recyclerview, and for this effect, there are many other ways of implementation, especially for adapter processing, but also hope to be able to communicate with you a lot. Thank you!

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.