LoginSignup
20

More than 5 years have passed since last update.

SwipeRefreshLayoutの使い方

Posted at

SwipeRefreshLayoutを導入してみたので簡単にまとめます。
まずはactivity_main

activity_main.xml

<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">

//ListViewやGridViewを<android.support.v4.widget.SwipeRefreshLayout>で囲む
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

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

上をやるだけでもswipeするとグルグルが出るようになる。
でも、情報更新されないしグルグル止まらない。
MainActivity.javaでそのあたりの設定をする。

MainActivity.java
public class MainActivity extends ActionBarActivity {

    private SwipeRefreshLayout mSwipeRefreshLayout;

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

        setContentView(R.layout.activity_main);


        /*この辺でadapterとかGridViewとか通信処理の設定やってる*/

        //SwipeRefreshLayoutとListenerの設定
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh);
        mSwipeRefreshLayout.setOnRefreshListener(mOnRefreshListener);
    }

    //swipeでリフレッシュした時の通信処理とグルグルを止める設定を書く
    private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            
        /*リフレッシュした時の通信処理を書く*/

        //setRefreshing(false)でグルグル終了できる
        mSwipeRefreshLayout.setRefreshing(false);
        }
    };

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20