SwipeRefreshLayout控件

SwipeRefreshLayout组件只接受一个子组件:即需要刷新的那个组件。它使用一个侦听机制来通知拥有该组件的监听器有刷新事件发生,换句话说我们的Activity必须实现通知的接口。该Activity负责处理事件刷新和刷新相应的视图。一旦监听者接收到该事件,就决定了刷新过程中应处理的地方。如果要展示一个“刷新动画”,它必须调用setRefrshing(true),否则取消动画就调用setRefreshing(false)

怎样使用SwipeRefreshLayout

<android.support.v4.widget.SwipeRefreshLayout

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:id="@+id/swipe">

    ……

</android.support.v4.widget.SwipeRefreshLayout>

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);

    final TextView rndNum = (TextView) findViewById(R.id.rndNum);

    swipeView.setColorScheme(android.R.color.holo_blue_dark, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_light);

    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override

        public void onRefresh() {

            swipeView.setRefreshing(true);

            Log.d("Swipe", "Refreshing Number");

            ( new Handler()).postDelayed(new Runnable() {

                @Override

                public void run() {

                    swipeView.setRefreshing(false);

                    double f = Math.random();

                    rndNum.setText(String.valueOf(f));

                }

            }, 3000);

        }

    });

}

在ListView上使用SwipeRefreshLayout

<LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/sample_main_layout">

    <ViewAnimator
          android:id="@+id/sample_output"
          android:layout_width="match_parent"
          android:layout_height="0px"
          android:layout_weight="1">

        <ScrollView
              style="@style/Widget.SampleMessageTile"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

            <TextView
                  style="@style/Widget.SampleMessage"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:paddingLeft="@dimen/horizontal_page_margin"
                  android:paddingRight="@dimen/horizontal_page_margin"
                  android:paddingTop="@dimen/vertical_page_margin"
                  android:paddingBottom="@dimen/vertical_page_margin"
                  android:text="@string/intro_message" />
        </ScrollView>

        <fragment
              android:name="com.example.android.common.logger.LogFragment"
              android:id="@+id/log_fragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />

    </ViewAnimator>

    <View
          android:layout_width="match_parent"
          android:layout_height="1dp"
          android:background="@android:color/darker_gray" />

    <FrameLayout
          android:id="@+id/sample_content_fragment"
          android:layout_weight="2"
          android:layout_width="match_parent"
          android:layout_height="0px" />

</LinearLayout>
package com.example.android.swiperefreshlayoutbasic;

import com.example.android.common.dummydata.Cheeses;
import com.example.android.common.logger.Log;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.List;

/**
 * A basic sample that shows how to use {@link android.support.v4.widget.SwipeRefreshLayout} to add
 * the ‘swipe-to-refresh‘ gesture to a layout. In this sample, SwipeRefreshLayout contains a
 * scrollable {@link android.widget.ListView} as its only child.
 *
 * <p>To provide an accessible way to trigger the refresh, this app also provides a refresh
 * action item.
 *
 * <p>In this sample app, the refresh updates the ListView with a random set of new items.
 */
public class SwipeRefreshLayoutBasicFragment extends Fragment {

    private static final String LOG_TAG = SwipeRefreshLayoutBasicFragment.class.getSimpleName();

    private static final int LIST_ITEM_COUNT = 20;

    /**
     * The {@link android.support.v4.widget.SwipeRefreshLayout} that detects swipe gestures and
     * triggers callbacks in the app.
     */
    private SwipeRefreshLayout mSwipeRefreshLayout;

    /**
     * The {@link android.widget.ListView} that displays the content that should be refreshed.
     */
    private ListView mListView;

    /**
     * The {@link android.widget.ListAdapter} used to populate the {@link android.widget.ListView}
     * defined in the previous statement.
     */
    private ArrayAdapter<String> mListAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Notify the system to allow an options menu for this fragment.
        setHasOptionsMenu(true);
    }

    // BEGIN_INCLUDE (inflate_view)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sample, container, false);

        // Retrieve the SwipeRefreshLayout and ListView instances
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);

        // BEGIN_INCLUDE (change_colors)
        // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
        mSwipeRefreshLayout.setColorScheme(
                R.color.swipe_color_1, R.color.swipe_color_2,
                R.color.swipe_color_3, R.color.swipe_color_4);
        // END_INCLUDE (change_colors)

        // Retrieve the ListView
        mListView = (ListView) view.findViewById(android.R.id.list);

        return view;
    }
    // END_INCLUDE (inflate_view)

    // BEGIN_INCLUDE (setup_views)
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        /**
         * Create an ArrayAdapter to contain the data for the ListView. Each item in the ListView
         * uses the system-defined simple_list_item_1 layout that contains one TextView.
         */
        mListAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                android.R.id.text1,
                Cheeses.randomList(LIST_ITEM_COUNT));

        // Set the adapter between the ListView and its backing data.
        mListView.setAdapter(mListAdapter);

        // BEGIN_INCLUDE (setup_refreshlistener)
        /**
         * Implement {@link SwipeRefreshLayout.OnRefreshListener}. When users do the "swipe to
         * refresh" gesture, SwipeRefreshLayout invokes
         * {@link SwipeRefreshLayout.OnRefreshListener#onRefresh onRefresh()}. In
         * {@link SwipeRefreshLayout.OnRefreshListener#onRefresh onRefresh()}, call a method that
         * refreshes the content. Call the same method in response to the Refresh action from the
         * action bar.
         */
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout");

                initiateRefresh();
            }
        });
        // END_INCLUDE (setup_refreshlistener)
    }
    // END_INCLUDE (setup_views)

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main_menu, menu);
    }

    // BEGIN_INCLUDE (setup_refresh_menu_listener)
    /**
     * Respond to the user‘s selection of the Refresh action item. Start the SwipeRefreshLayout
     * progress bar, then initiate the background task that refreshes the content.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_refresh:
                Log.i(LOG_TAG, "Refresh menu item selected");

                // We make sure that the SwipeRefreshLayout is displaying it‘s refreshing indicator
                if (!mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(true);
                }

                // Start our refresh background task
                initiateRefresh();

                return true;
        }

        return super.onOptionsItemSelected(item);
    }
    // END_INCLUDE (setup_refresh_menu_listener)

    // BEGIN_INCLUDE (initiate_refresh)
    /**
     * By abstracting the refresh process to a single method, the app allows both the
     * SwipeGestureLayout onRefresh() method and the Refresh action item to refresh the content.
     */
    private void initiateRefresh() {
        Log.i(LOG_TAG, "initiateRefresh");

        /**
         * Execute the background task, which uses {@link android.os.AsyncTask} to load the data.
         */
        new DummyBackgroundTask().execute();
    }
    // END_INCLUDE (initiate_refresh)

    // BEGIN_INCLUDE (refresh_complete)
    /**
     * When the AsyncTask finishes, it calls onRefreshComplete(), which updates the data in the
     * ListAdapter and turns off the progress bar.
     */
    private void onRefreshComplete(List<String> result) {
        Log.i(LOG_TAG, "onRefreshComplete");

        // Remove all items from the ListAdapter, and then replace them with the new items
        mListAdapter.clear();
        for (String cheese : result) {
            mListAdapter.add(cheese);
        }

        // Stop the refreshing indicator
        mSwipeRefreshLayout.setRefreshing(false);
    }
    // END_INCLUDE (refresh_complete)

    /**
     * Dummy {@link AsyncTask} which simulates a long running task to fetch new cheeses.
     */
    private class DummyBackgroundTask extends AsyncTask<Void, Void, List<String>> {

        static final int TASK_DURATION = 3 * 1000; // 3 seconds

        @Override
        protected List<String> doInBackground(Void... params) {
            // Sleep for a small amount of time to simulate a background-task
            try {
                Thread.sleep(TASK_DURATION);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Return a new random list of cheeses
            return Cheeses.randomList(LIST_ITEM_COUNT);
        }

        @Override
        protected void onPostExecute(List<String> result) {
            super.onPostExecute(result);

            // Tell the Fragment that the refresh has completed
            onRefreshComplete(result);
        }

    }
}
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            SwipeRefreshLayoutBasicFragment fragment = new SwipeRefreshLayoutBasicFragment();
            transaction.replace(R.id.sample_content_fragment, fragment);
            transaction.commit();
        }
    }

时间: 2024-12-12 06:53:03

SwipeRefreshLayout控件的相关文章

Android全新的SwipeRefreshLayout控件教程

SwipeRefreshLayout感觉是Google在吸收了PullToRefresh-ListView,ActionBarPullToRefresh之后实现的google风格的刷新控件,那花花绿绿的穿越条,浓浓的google味. 迁移到Android studio后就必须使用AppCompat_v7 21+ ,切换了之后你就会发现一些有趣的变化,比如说这个SwipeRefreshLayout,就进化成了一个圆. 那么就来看下怎么使用SwipeRefreshLayout吧! 首先需要在布局里面

下拉刷新控件——SwipeRefreshLayout

1.SwipeRefreshLayout控件在v4包下 布局: <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/id_swipe_ly"> //这里是给需要添加下拉刷新的布局 比如ListView <ListView></> </> 2.自定义 下拉图标的颜色 id_swipe_ly.setColorSchemeResources( android.R.colo

Android——谷歌官方下拉刷新控件SwipeRefreshLayout(转)

转自:http://blog.csdn.net/zouzhigang96/article/details/50476402 版权声明:本文为博主原创文章,未经博主允许不得转载. 前言: 如今谷歌推出了更官方的下拉刷新控件, 这无疑是对安卓开发人员来说是个好消息,很方便的使用这个SwipeRefreshLayout控件实现下拉刷新功能.Android4.0以下的版本需要用到 Android-support-v4.jar包才能用到 android-support-v4.jar 包下载地址:http:

使用谷歌提供的SwipeRefreshLayout下拉控件,并自定义实现下拉加载的功能

package com.loaderman.swiperefreshdemo; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.View;

Android下拉刷新控件SwipeRefreshLayout源码浅析

SwipeRefreshLayout是Android官方的下拉刷新控件,使用简单,界面美观,不熟悉的朋友可以随便搜索了解一下,这里就不废话了,直接进入正题. 这种下拉刷新控件的原理不难,基本就是监听手指的运动,获取手指的坐标,通过计算判断出是哪种操作,然后就是回调相应的接口了.SwipeRefreshLayout是继承自ViewGroup的,根据Android的事件分发机制,触摸事件应该是先传递到ViewGroup,根据onInterceptTouchEvent的返回值决定是否拦截事件的,那么就

PullToRefresh开源控件和5.0新特性SwipeRefreshLayout的对比使用

PullToRefresh开源控件可以实现下拉和上拉刷新数据,而后者SwipeRefreshLayout主要用于下拉刷新,知乎的首页刷新数据用的就是这个控件. 一,先介绍PullToRefresh开源控件的使用 PullToRefresh开源控件可以实现下拉和上拉刷新数据,在项目中首先要导入这个包,可以先从github上进行下载,之后在Android Studio中进行导入,之前试了直接导入总会报错,后来直接右键New Module,新建android library即可,按照PullToRef

Android SwipeRefreshLayout 官方下拉刷新控件介绍

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/24521483 以下App基本都有下拉刷新的功能,曾经基本都使用XListView或者自己写一个下拉刷新,最近Google提供了一个官方的下拉刷新控件SwipeRefreshLayout,我感觉还不错啊,见惯了传统的下拉刷新,这个反而给人耳目一新的感觉(貌似知乎的APP已经使用这样的下拉刷新了). Google也在官方站点给出了V4的兼容包: 顺便看一眼API呗: 和XlistV

Android SwipeRefreshLayout下拉刷新控件源码简单分析

咱们在做Android APP开发的时候经常碰到有下拉刷新和上拉加载跟多的需求,这篇文章咱们先说说下来刷新,咱们就以google的原生的下拉刷新控件SwipeRefreshLayout来看看大概的实现过程. SwipeRefreshLayout是google自己推出的下拉刷新控件.使用起来也非常的简单,在满足条件的情况下下拉的时候会显示一个圆形的loading的动画效果,然后回调到上层,上层自己做刷新的一系列的处理,处理结束后调用SwipeRefreshLayout的setRefreshing(

android官方下拉刷新控件SwipeRefreshLayout的使用

可能开发安卓的人大多数都用过很多下拉刷新的开源组件,但是今天用了官方v4支持包的SwipeRefreshLayout觉得效果也蛮不错的,特拿出来分享. 简介:SwipeRefreshLayout组件只接受一个子组件:即需要刷新的那个组件.它使用一个侦听机制来通知拥有该组件的监听器有刷新事件发生,换句话说我们的Activity必须实现通知的接口.该Activity负责处理事件刷新和刷新相应的视图.一旦监听者接收到该事件,就决定了刷新过程中应处理的地方.如果要展示一个“刷新动画”,它必须调用setR