Android PullToRefresh (ListView GridView pull-down refresh) Usage Details, listviewgridview

Source: Internet
Author: User

Android PullToRefresh (ListView GridView pull-down refresh) Usage Details, listviewgridview

Reprinted please indicate the source: bytes]

A group of friends chatted today and occasionally mentioned the git hub control: pull-to-refresh. If you are interested, the function in this example is extremely powerful and supports many controls. This blog introduces ListView and GridView using pull-to-rerfesh to implement pull-down refresh and pull-up loading.

1. ListView pull-down refresh Quick Start

Pull-to-refresh encapsulates ListView, which is called PullToRefreshListView. Its usage is no different from that of listview. See the demo below.

Layout file:

<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" >    <com.handmark.pulltorefresh.library.PullToRefreshListView        xmlns:ptr="http://schemas.android.com/apk/res-auto"        android:id="@+id/pull_refresh_list"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:cacheColorHint="#00000000"        android:divider="#19000000"        android:dividerHeight="4dp"        android:fadingEdge="none"        android:fastScrollEnabled="false"        android:footerDividersEnabled="false"        android:headerDividersEnabled="false"        android:smoothScrollbar="true" >    </com.handmark.pulltorefresh.library.PullToRefreshListView></RelativeLayout>

A PullToRefreshListView is declared, and all its attributes are ListView without any other attributes. Of course, PullToRefreshListView also provides many configuration attributes, which will be detailed later.

Activity Code:

Package com. example. zhy_pulltorefreash_chenyoca; import java. util. permission list; import android. app. activity; import android. OS. asyncTask; import android. OS. bundle; import android. text. format. dateUtils; import android. widget. arrayAdapter; import android. widget. listView; import com. handmark. pulltorefresh. library. pullToRefreshBase; import com. handmark. pulltorefresh. library. pullToRefreshBase. onRefreshListener; import com. handmark. pulltorefresh. library. pullToRefreshListView; public class extends Activity {private pull list <String> mListItems;/*** pull refresh control */private PullToRefreshListView mPullRefreshListView; private ArrayAdapter <String> mAdapter; private int mItemCount = 9; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the control mPullRefreshListView = (PullToRefreshListView) findViewById (R. id. pull_refresh_list); // initialize the data initDatas (); // set the adapter mAdapter = new ArrayAdapter <String> (this, android. r. layout. simple_list_item_1, mListItems); mPullRefreshListView. setAdapter (mAdapter); // sets the listener event mPullRefreshListView. setOnRefreshListener (new OnRefreshListener <ListView> () {@ Overridepublic void onRefresh (PullToRefreshBase <ListView> refreshView) {String label = DateUtils. formatDateTime (getApplicationContext (), System. currentTimeMillis (), DateUtils. FORMAT_SHOW_TIME | DateUtils. FORMAT_SHOW_DATE | DateUtils. FORMAT_ABBREV_ALL); // display the last update time refreshView. getLoadingLayoutProxy (). setLastUpdatedLabel (label); // simulate the loading task new getdatatask(cmd.exe cute () ;});} private void initDatas () {// initialize data and data source mListItems = new shortlist <String> (); for (int I = 0; I <mItemCount; I ++) {mListItems. add ("" + I) ;}} private class GetDataTask extends AsyncTask <Void, Void, String >{@ Overrideprotected String doInBackground (Void... params) {try {Thread. sleep (2000);} catch (InterruptedException e) {} return "" + (mItemCount ++);} @ Overrideprotected void onPostExecute (String result) {mListItems. add (result); mAdapter. notifyDataSetChanged (); // Call onRefreshComplete when the list has been refreshed. mPullRefreshListView. onRefreshComplete ();}}}

The code is extremely simple. Get the PullToRefreshListView control and set the dataset like ListView. Of course, we have a pull-down refresh, so we must set a pull-down refresh callback:

SetOnRefreshListener (new OnRefreshListener <ListView> (){}

We simulate an asynchronous task in the callback and load an Item.

:


In the drop-down list, execute the GetDataTask task. After the task is executed, call mPullRefreshListView. onRefreshComplete () in onPostExecute to complete the refresh.

Whether to implement pull-down refresh in minutes. Of course, you may have a question: can text on the drop-down and refresh indicators be customized? Can the image be changed to an arrow? What if I say I want to load more files? Will be added later ~

2. Add pull-on and load more

If you want to pull and load more files, you must first add an attribute to the declaration attribute of the layout file to specify the current drop-down mode:

<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" >    <com.handmark.pulltorefresh.library.PullToRefreshListView        xmlns:ptr="http://schemas.android.com/apk/res-auto"        android:id="@+id/pull_refresh_list"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:cacheColorHint="#00000000"        android:divider="#19000000"        android:dividerHeight="4dp"        android:fadingEdge="none"        android:fastScrollEnabled="false"        android:footerDividersEnabled="false"        android:headerDividersEnabled="false"        android:smoothScrollbar="true"        ptr:ptrMode="both" >    </com.handmark.pulltorefresh.library.PullToRefreshListView></RelativeLayout>
We have added a property: ptr: ptrMode = "both", which means that both the pull-up and the drop-down are supported.

Optional values: disabled, pullFromStart, pullFromStart, pullFromEnd, and both ), manualOnly (manual triggering only)

Of course, if you do not like to specify it in the layout file, you can use code settings and write: mPullRefreshListView. setMode (Mode. BOTH) in onCreate; // set the Mode you need

If the mode is set to both directions, callback must be set for the pull-up and pull-down respectively. See the following code:

Package com. example. zhy_pulltorefreash_chenyoca; import java. util. permission list; import android. app. activity; import android. OS. asyncTask; import android. OS. bundle; import android. text. format. dateUtils; import android. util. log; import android. widget. arrayAdapter; import android. widget. listView; import com. handmark. pulltorefresh. library. pullToRefreshBase; import com. handmark. pulltorefresh. library. pullToRefreshBase. mode; import com. handmark. pulltorefresh. library. pullToRefreshBase. onRefreshListener; import com. handmark. pulltorefresh. library. pullToRefreshBase. onRefreshListener2; import com. handmark. pulltorefresh. library. pullToRefreshListView; public class extends Activity {private pull list <String> mListItems;/*** pull refresh control */private PullToRefreshListView mPullRefreshListView; private ArrayAdapter <String> mAdapter; private int mItemCount = 9; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the control mPullRefreshListView = (PullToRefreshListView) findViewById (R. id. pull_refresh_list); mPullRefreshListView. setMode (Mode. BOTH); // initialize the data initDatas (); // set the adapter mAdapter = new ArrayAdapter <String> (this, android. r. layout. simple_list_item_1, mListItems); mPullRefreshListView. setAdapter (mAdapter); mPullRefreshListView. setOnRefreshListener (new OnRefreshListener2 <ListView> () {@ Overridepublic void onPullDownToRefresh (PullToRefreshBase <ListView> refreshView) {Log. e ("TAG", "Expiration"); // write the new getdatatask(.exe cute () ;}@ Overridepublic void onPullUpToRefresh (PullToRefreshBase <ListView> refreshView) {Log. e ("TAG", "onPullUpToRefresh"); // write here to pull more tasks new getdatatask(cmd.exe cute () ;}});} private void initDatas () {// initialize data and data source mListItems = new shortlist <String> (); for (int I = 0; I <mItemCount; I ++) {mListItems. add ("" + I) ;}} private class GetDataTask extends AsyncTask <Void, Void, String >{@ Overrideprotected String doInBackground (Void... params) {try {Thread. sleep (2000);} catch (InterruptedException e) {} return "" + (mItemCount ++);} @ Overrideprotected void onPostExecute (String result) {mListItems. add (result); mAdapter. notifyDataSetChanged (); // Call onRefreshComplete when the list has been refreshed. mPullRefreshListView. onRefreshComplete ();}}

There is only one difference from the first code, and it may be hard to find:
MPullRefreshListView. setOnRefreshListener (new OnRefreshListener2 <ListView> () {}); note that the interface type here is OnRefreshListener2, with 2 more. This interface contains two methods, one pull callback and one pull callback. Now, we have successfully added the pull-up and drop-down operations, and can control the callback Code respectively.

:


Is it easy ~ Note: If you need to execute the same code as the pull-up and drop-down operations, you can register the OnRefreshListener interface. Both the pull-up and drop-down operations will execute the same method.

Next, we will introduce how to use a drop-down box to refresh and load more GridView and custom styles ~

3. PullToRefreshGridView)

The same pull-to-refresh encapsulates the GridView as: PullToRefreshGridView. Usage is the same as that of PullToRefreshListView ~

First, check the main layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <!-- The PullToRefreshGridView replaces a standard GridView widget. -->    <com.handmark.pulltorefresh.library.PullToRefreshGridView        xmlns:ptr="http://schemas.android.com/apk/res-auto"        android:id="@+id/pull_refresh_grid"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:columnWidth="100dp"        android:gravity="center_horizontal"        android:horizontalSpacing="1dp"        android:numColumns="auto_fit"        android:stretchMode="columnWidth"        android:verticalSpacing="1dp"        ptr:ptrDrawable="@drawable/ic_launcher"        ptr:ptrMode="both" /></LinearLayout>
Layout file of items in PullToRefreshGridView:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/id_grid_item_text"    android:layout_width="100dp"    android:gravity="center"    android:textColor="#ffffff"    android:textSize="16sp"    android:background="#000000"    android:layout_height="100dp" />

The following is the Activity code:

Public class extends Activity {private javaslist <String> mListItems; private PullToRefreshGridView failed; private ArrayAdapter <String> mAdapter; private int mItemCount = 10; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_ptr_grid); // obtain the control mPullRefreshListView = (PullToRefreshGridView) findViewById (R. id. pull_refresh_grid); // initialize data and data source initDatas (); mAdapter = new ArrayAdapter <String> (this, R. layout. grid_item, R. id. id_grid_item_text, mListItems); mPullRefreshListView. setAdapter (mAdapter); mPullRefreshListView. setOnRefreshListener (new OnRefreshListener2 <GridView> () {@ Overridepublic void onPullDownToRefresh (PullToRefreshBase <GridView> refreshView) {Log. e ("TAG", "onPullDownToRefresh"); // Do work toString label = DateUtils. formatDateTime (getApplicationContext (), System. currentTimeMillis (), DateUtils. FORMAT_SHOW_TIME | DateUtils. FORMAT_SHOW_DATE | DateUtils. FORMAT_ABBREV_ALL); // Update the LastUpdatedLabelrefreshView. getLoadingLayoutProxy (). setLastUpdatedLabel (label); new getdatatask(cmd.exe cute () ;}@ Overridepublic void onPullUpToRefresh (PullToRefreshBase <GridView> refreshView) {Log. e ("TAG", "onPullUpToRefresh"); // Do work to refresh // the list here. new getdatatask(cmd.exe cute () ;}}) ;}private void initDatas () {mListItems = new shortlist <String> (); for (int I = 0; I <mItemCount; I ++) {mListItems. add (I + "") ;}} private class GetDataTask extends AsyncTask <Void, Void, Void >{@ Overrideprotected Void doInBackground (Void... params) {try {Thread. sleep (2000);} catch (InterruptedException e) {} return null;} @ Overrideprotected void onPostExecute (Void result) {mListItems. add ("" + mItemCount ++); mAdapter. notifyDataSetChanged (); // Call onRefreshComplete when the list has been refreshed. mPullRefreshListView. onRefreshComplete ();}}

Basically, there is no difference in the above example. Let's take a look:

The effect is good. If you are more careful, you will find that the picture of the pull-down refresh circle turns into a robot, because I set it in the layout file:

 <com.handmark.pulltorefresh.library.PullToRefreshGridView        ptr:ptrDrawable="@drawable/ic_launcher"        ...        />

Of course, this is the effect of rotation. It is also commonly used. The effect of an arrow inversion is actually very simple, and an attribute:

Ptr: ptrAnimationStyle = "flip"

Remove the ptr: ptrDrawable = "@ drawable/ic_launcher" attribute. If you want to use the default Arrow, you can also customize it.

After adding, the arrow is like this:

Ptr: ptrAnimationStyle; values: flip (flip animation) and rotate (rotation animation ).

Ptr: ptrDrawable indicates the setting icon.


4. Custom drop-down indicator text content and other effects

After mPullRefreshListView is initialized, you can use mPullRefreshListView. getLoadingLayoutProxy () to obtain an ILoadingLayout object. This object can set styles and texts in various indicators.

ILoadingLayout startLabels = mPullRefreshListView. getLoadingLayoutProxy (); startLabels. setPullLabel ("You can pull, pull... "); // The startLabels. setRefreshingLabel ("good luck, refreshing... "); // startLabels when refreshing. setReleaseLabel ("You dare to release, I dare to refresh... "); // The prompt displayed when the distance is reached

If you are careful, you will find that the last refresh time we set previously has been used:

// Update the LastUpdatedLabel
RefreshView. getLoadingLayoutProxy (). setLastUpdatedLabel (label );

The effect is as follows:



By default, the words on the top and drop-down are changed at the same time. What if I want to change them separately?

Private void initIndicator () {ILoadingLayout startLabels = mPullRefreshListView. getLoadingLayoutProxy (true, false); startLabels. setPullLabel ("You can pull, pull... "); // The startLabels. setRefreshingLabel ("good luck, refreshing... "); // startLabels when refreshing. setReleaseLabel ("You dare to release, I dare to refresh... "); // The ILoadingLayout endLabels = mPullRefreshListView prompt is displayed when the distance is reached. getLoadingLayoutProxy (false, true); endLabels. setPullLabel ("You can pull, pull 2... "); // The prompt" endLabels "is displayed when you pull down the page. setRefreshingLabel ("good luck, refreshing 2... "); // endLabels. setReleaseLabel ("You dare to release, I dare to refresh 2... "); // The prompt displayed when the distance is reached}

MPullRefreshListView. getLoadingLayoutProxy (true, false); receives two parameters: true and false, and returns the ILoadingLayout parameter in the drop-down list. If the value is false, the result of setting up pulling is returned.

5. common attributes

Of course, pull-to-refresh can also define some attributes in xml:

PtrMode, ptrDrawable, and ptrAnimationStyle have been described above.

PtrRefreshableViewBackground sets the background color of the entire mPullRefreshListView.

PtrHeaderBackground: Set the background color of the drop-down Header or Footer.

PtrHeaderTextColor is used to set the color of the text in the Header and Footer.

PtrHeaderSubTextColor is used to set the color of the last refresh time in the Header and Footer.

If ptrShowIndicator is set to true, the icon, upper right corner and lower right corner appear in mPullRefreshListView, which is quite interesting.

PtrHeaderTextAppearance and ptrSubHeaderTextAppearance respectively set the font color of the headers or Footer.

PtrRotateDrawableWhilePulling when the animation is set to rotate, the drop-down shows whether to rotate.

Whether to allow ListView or GridView scrolling when ptrScrollingWhileRefreshingEnabled is refreshed. True is better.

PtrListViewExtrasEnabled determines the Header. Footer adds mPullRefreshListView in the following way. true indicates that the headView is added, that is, the headers will be refreshed and rolled together when scrolling.

The last two are actually very important for the user experience. If you want to set them, consider it ~.Select other attributes.

Note: many of the above attributes can be controlled by code. If necessary, you can directly view the mPullRefreshListView. set attribute name.

The above are all the attributes supported by pull-to-refresh ~~

Defines a bunch of effects:


The icon in the upper right and lower right is ptrShowIndicator. Now, you can explain the configuration to the above attributes as needed.


The example downloaded on github is dependent on three projects, one basic library_pullToRefresh, one PullToRefreshViewPager, And the other PullToRefreshListFragment;

The example described above only depends on library_pullToRefresh. The other two dependencies do not need to be imported.



Well, if you think this blog is useful to you, just like it ~ Leave a message.


Download source code





The android ListView has been optimized by third-party class libraries.

Android-pulltorefresh is a powerful open-source project for pulling and refreshing, and supports pull-down and refreshing of various controls.
Android-pulltorefresh-listview pull-down refresh ListView
DropDownListView pull-down refresh and slide to the bottom to load more ListView
DragSortListView
SwipeListView supports defining the left and right sliding events of ListView, the left and right sliding displacement, and the animation time.
Android-SwipeToDismiss slide Item disappears ListView
StickyListHeaders GroupName
Pinned-section-listview
PinnedHeaderListView
QuickReturnHeader ListView/ScrollView header or footer
IndexableListView
CustomFastScrollView
Ndroid-ScrollBarPanel the fixed Panel indicator displayed next to the scrollbar when the ListView slides
The SlideExpandableListView user clicks the listView item to slide out of the fixed area, and the area of other items shrinks.
JazzyListView ListView and GridView item enter the screen with special animation Effects
ListViewAnimations: A ListView with an Item display animation. The animation includes the bottom fly in, other oblique fly in, lower fly in, gradient disappear, sliding Delete, etc.
DevsmartLib-Android horizontal ListView
This is the usage of my favorite ListView. You can search it on github.

 
Understanding about the android program and the selection of controls

I will not talk about other things. I will only say 4th: PullToRefresh (pull-down refresh control, and 1 is a whole ). Github.com/..efresh

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.