目的
Androidアプリ(Java)について
画面を下に引っ張ると処理が行われる(一般的には、その画面の更新処理)を実装するためのメモ
実装
サンプル動画
サンプルとしては以下となります。
背景も白なので少しわかりにくいですが。下にスワイプするたびに中央の数値が増加!
xml
まず、対象のxmlファイルについて、View
などをSwipeRefreshLayout
で囲む
ListView
などで使う方が多いかと
サンプルはTextViewのみ。
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipelayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textcount"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="1"
android:textSize="32sp"
android:gravity="center"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Javaファイル
対象のjavaファイルにてSwipeRefreshLayout.OnRefreshListener
を実装します。
public class XXX implements SwipeRefreshLayout.OnRefreshListener {
//...
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = findViewById(R.id.swipelayout);
swipeRefreshLayout.setOnRefreshListener(this);
//..
}
//...
}
画面を引っ張るとonRefresh
が呼ばれるので、引っ張った時に行う処理を実装する。
@Override
public void onRefresh() {
countSwipe += 1;
countTextView.setText(String.valueOf(countSwipe));
swipeRefreshLayout.setRefreshing(false);
}
swipeRefreshLayout.setRefreshing(false);
は、更新アイコンを閉じる処理なので、処理が終わったタイミングで設定するようにする。
メモとしては以上です。