Android Support v7 provides staggered grid layout development examples

Source: Internet
Author: User

Android Support v7 provides staggered grid layout development examples
This article describes how to use the RecycleView and staggered layout (usually waterfall stream layout) provided by Android Support v7 and how to handle event listening. 1. involved open-source libraries include: Fresco: Facebook open-source components are not generally powerful image loading Component Library Bufferknife: Android View and event binding library, which are completed by annotation. APT processes annotation documents during compilation. 2. Configure the Android Studio module and build. gradle:

apply plugin: 'com.android.application'android {    compileSdkVersion 21    buildToolsVersion '21.1.2'    defaultConfig {        applicationId 'secondriver.sdk'        minSdkVersion 16        targetSdkVersion 21        versionCode 1        versionName '1.0'    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }    packagingOptions {        exclude 'META-INF/services/javax.annotation.processing.Processor'    }    lintOptions {        disable 'InvalidPackage'    }}dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    compile 'com.android.support:appcompat-v7:21.0.3'    compile 'com.android.support:recyclerview-v7:21.0.3@aar'    compile 'com.android.support:cardview-v7:21.0.3@aar'    compile 'com.facebook.fresco:fresco:0.8.0'    compile 'com.jakewharton:butterknife:7.0.1'    testCompile 'junit:junit:4.12'}

 

3. layout file main layout file: activity_recycleview.xml contains a RecycleView, which will be used as the main screen component.
<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:id="@+id/swipe_refresh_layout"                xmlns:android="http://schemas.android.com/apk/res/android"                android:layout_width="match_parent"                android:layout_height="wrap_content">    <android.support.v7.widget.RecyclerView        android:id="@+id/recycler_view"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:scrollbars="vertical"        /></RelativeLayout>

 

RecycleView displays different la s by setting different layout manager objects, such as android. support. v7.widget. linearLayoutManager can achieve the layout of ListView android. support. v7.widget. gridLayoutManager can achieve the layout of the GridView android. support. v7.widget. staggeredGridLayoutManager can be used to implement the layout file (layout of each view displayed in RecycleView): item_recycelview.xml uses com. android. support: The CardView package provides a CardView frame container layout that includes an ImageView and TextView as the layout of each view of RecycleView.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              xmlns:card_view="http://schemas.android.com/apk/res-auto"              xmlns:fresco="http://schemas.android.com/tools"              android:layout_width="match_parent" android:layout_height="match_parent"              android:gravity="center">    <android.support.v7.widget.CardView        android:id="@+id/card_view"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        card_view:cardCornerRadius="4dp"        card_view:cardUseCompatPadding="true">        <RelativeLayout            android:layout_width="match_parent"            android:layout_height="wrap_content" android:orientation="vertical">            <com.facebook.drawee.view.SimpleDraweeView                android:id="@+id/info_image"                android:layout_width="300dp"                android:layout_height="420dp"                fresco:actualImageScaleType="centerCrop"                fresco:placeholderImage="@mipmap/ic_launcher"                fresco:roundAsCircle="false"                fresco:roundBottomLeft="true"                fresco:roundBottomRight="true"                fresco:roundTopLeft="true"                fresco:roundTopRight="true"                fresco:roundedCornerRadius="1dp"                fresco:roundingBorderWidth="2dp"                />            <TextView                android:id="@+id/info_text"                android:layout_width="200dp"                android:layout_height="80dp"                android:textSize="20sp"                android:textColor="@android:color/holo_blue_dark"                android:textAppearance="?android:attr/textAppearanceMedium"                android:layout_alignLeft="@id/info_image"                android:layout_alignRight="@id/info_image"                android:layout_below="@id/info_image"                android:gravity="left|center_vertical"/>        </RelativeLayout>    </android.support.v7.widget.CardView></LinearLayout>

 

The ImageView component uses the view component provided by the Fresco library. 4. Implement Activity and fill in data. 4.1 The data of each view in RecycleView is composed of text information + image address (url, file, resId). In this example, Url-based network images are used.
/*** View data object */static class Pair {public String text; public String url; public Pair (String text, String url) {this. text = text; this. url = url ;}}

 

4.2 RecycleView data fill for each view in China, that is, the Adapter custom Adapter needs to implement the RecycleView. Adapter class.
Static class RecycleViewAdapter extends RecyclerView. adapter <RecyclerView. viewHolder> {/*** Click Event listener */public interface OnRecycleViewItemClickListener {void onRecycleViewItemClick (View, int position) in the view item of RecycleView );} private ArrayList <Pair> items = new ArrayList <> (); private OnRecycleViewItemClickListener mOnRecycleViewItemClickListener; public RecycleViewAdapter (ArrayList <Pair> items ){ This. items = items ;}@ Override public RecyclerView. viewHolder onCreateViewHolder (ViewGroup parent, int viewType) {View = LayoutInflater. from (parent. getContext ()). inflate (R. layout. item_recyclerview, parent, false); return new RecycleViewItemHolder (view, mOnRecycleViewItemClickListener);} @ Override public void onBindViewHolder (RecyclerView. viewHolder holder, int position) {Pair pair = items. Get (position); (RecycleViewItemHolder) holder ). setContent (pair) ;}@ Override public int getItemCount () {return items. size ();} public void setOnRecycleViewItemClickListener (OnRecycleViewItemClickListener onItemClickListener) {if (null! = OnItemClickListener) {this. mOnRecycleViewItemClickListener = onItemClickListener ;}}}

 

Mainly implements onCreateViewHolder and onBindViewHolder methods. Because RecycleView does not provide adding listening events for view items, a custom event listening interface is provided here. You can set event listening when instantiating the adapter. 4.3 When creating ViewHolder, you must use the custom ViewHolder class to inherit RecycleView. ViewHolder.
static class RecycleViewItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {        @Bind(R.id.info_text)        public TextView infoTextView;        @Bind(R.id.info_image)        public SimpleDraweeView draweeView;        private RecycleViewAdapter.OnRecycleViewItemClickListener onItemClickListener;        public RecycleViewItemHolder(View itemView, RecycleViewAdapter.OnRecycleViewItemClickListener onItemClickListener) {            super(itemView);            ButterKnife.bind(this, itemView);            this.onItemClickListener = onItemClickListener;            itemView.setOnClickListener(this);        }        public void setContent(Pair pair) {            infoTextView.setText(pair.text);            draweeView.setImageURI(Uri.parse(pair.url));        }        @Override        public void onClick(View v) {            if (null != onItemClickListener) {                onItemClickListener.onRecycleViewItemClick(v, getPosition());            }        }    }

 

The OnRecycleViewItemClickListener object is passed in the constructor method, and the ViewHolder is customized to implement the OnClickListener interface. By setting the OnClickListener listener event for the itemView object, The onClick event is handled by the OnRecycleViewItemClickListener object, to register click events for itemView in RecycleView. If you do not use this method to add event listening, you do not need to use the Custom listening interface and custom ViewHolder to implement the event listening interface and event processing. In addition, after obtaining the itemView, you can add event listening through the component I acquisition component. You can also access each component through the obtained custom ViewHolder. 4.4 specific implementation of Activity
Package secondriver. sdk. activity; import android. app. activity; import android.net. uri; import android. OS. bundle; import android. support. v7.widget. defaultItemAnimator; import android. support. v7.widget. recyclerView; import android. support. v7.widget. staggeredGridLayoutManager; import android. util. log; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widg Et. textView; import android. widget. toast; import com. facebook. drawee. view. simpleDraweeView; import java. util. arrayList; import java. util. arrays; import java. util. random; import butterknife. bind; import butterknife. butterKnife; import secondriver. sdk. r;/*** Author: secondriver * Created: 2015/11/18 */public class RecycleViewActivity extends Activity {private static final String TAG = RecyclerView. class. GetName (); private static final String [] RES_URL = new String [] {"http://p1.wmpic.me/article/2015/11/16/1447644849_hySANEEF.jpg", // reduce space, save 14 image URLs here}; @ Bind (R. id. recycler_view) public RecyclerView mRecycleView; private final int PRE_SCREEN_NUMBER = 6; private final int SPAN_COUNT = 2; private int previuslastindex = 0; private boolean comment = false; private recycleviewmadadapter apter; Private ArrayList <Pair> mItem = new ArrayList <> (); // The management object of the staggered grid layout, which is usually called the waterfall flow layout private StaggeredGridLayoutManager mLayoutManager; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_recyclerview); ButterKnife. bind (this); Fresco. initialize (this); // important. Fresco performs a series of initialization tasks. initRecycleView ();} private void initRecycleView (){ MLayoutManager = new StaggeredGridLayoutManager (SPAN_COUNT, StaggeredGridLayoutManager. VERTICAL); mRecycleView. setLayoutManager (mLayoutManager); mAdapter = new RecycleViewAdapter (mItem); loadData (false); mRecycleView. setAdapter (mAdapter); mRecycleView. setItemAnimator (new DefaultItemAnimator (); // click the View item of RecycleView to listen to mAdapter. setOnRecycleViewItemClickListener (new RecycleViewAdapter. onRecycleVie WItemClickListener () {@ Override public void onRecycleViewItemClick (View view, int position) {long id = mRecycleView. getChildItemId (view); Log. d (TAG, "View Item Root view:" + View. getClass (). getName () + ", position =" + position + "ViewHolder_Id =" + id); // you can use findViewById to find the element SimpleDraweeView draweeView = (SimpleDraweeView) View in the view item. findViewById (R.id.info _ image); if (null! = DraweeView) {draweeView. setImageURI (Uri. parse (RES_URL [0]); Toast. makeText (RecycleViewActivity. this, "using findViewById to find elements in a View item", Toast. LENGTH_LONG ). show ();} RecycleViewItemHolder recycleViewItemHolder = (RecycleViewItemHolder) mRecycleView. findViewHolderForPosition (position); if (null! = RecycleViewItemHolder) {recycleViewItemHolder. infoTextView. setText ("find the element in the View item through ViewHolder") ;}}); // pull-down refresh to append the content to mRecycleView. setOnScrollListener (new RecyclerView. onScrollListener () {@ Override public void onScrollStateChanged (RecyclerView recyclerView, int newState) {super. onScrollStateChanged (recyclerView, newState); if (newState = RecyclerView. SCROLL_STATE_IDLE) {if (isPullToBottom () & isSlidingToLast) {if (mItem. size ()> 36) {// maximum data volume Toast. makeText (RecycleViewActivity. this, "No data", Toast. LENGTH_LONG ). show (); return;} else {loadData (false); Log. d (TAG, "policyitemrangeinserted startPosition =" + previuslastindex); mAdapter. policyitemrangeinserted (previuslastindex, PRE_SCREEN_NUMBER) ;}} if (newState = RecyclerView. SCROLL_STATE_SETTLING) {Log. d (TAG, "settling") ;}@ Override public void onScrolled (RecyclerView recyclerView, int dx, int dy) {super. onScrolled (recyclerView, dx, dy); isscyclingtolast = dy> 0; // pull up, Log down. d (TAG, "dx =" + dx + "dy =" + dy + "isSlidingToLast =" + isSlidingToLast) ;}} private boolean isPullToBottom () {int [] lastIndexs = mLayoutManager. findLastCompletelyVisibleItemPositions (null); Log. d (TAG, "last item =" + Arrays. toString (lastIndexs) + ", have item =" + mAdapter. getItemCount (); int maxIndex = mAdapter. getItemCount ()-1; for (int I: lastIndexs) {if (I = maxIndex) {return true ;}return false ;} private void loadData (boolean isClear) {if (isClear) {mItem. clear ();} previuslastindex = mItem. size (); Random r = new Random (); for (int index = 0; index <PRE_SCREEN_NUMBER & index <RES_URL.length; index ++) {mItem. add (new Pair ("Card" + (previuslastindex + index), RES_URL [r. nextInt (RES_URL.length)]);} Log. d (TAG, "mItem count =" + mItem. size ());}}

 

Note: before using the ItemView data of RecycleView, the Pair Object Management storage Fresco library is configured by default, Fresco needs to be initialized. initialize (Context) implements two event listeners. One OnScrollerListener is provided by RecycleView to implement pull-down refresh. The other OnRecycleViewItemClickListener is provided by the custom RecycleViewAdpater to change the image by clicking itemView) and text (TextView ). For more information about how to use the Butterknife and Fresco libraries, see the documentation on its Github.

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.