Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidにスワイプリフレッシュレイアウト(SwipeRefreshLayout)を実装する方法

この記事では、Kotlinを使用してAndroidアプリにスワイプリフレッシュレイアウト(SwipeRefreshLayout)を実装する方法を、サンプルコードとともにステップごとに解説します。

SwipeRefreshLayoutは、画面を下方向にスワイプするだけでデータを再読み込みできる「Pull to Refresh(引っ張って更新)」操作を簡単に実装できる公式ウィジェットです。ニュースアプリやSNSなどで頻繁に使われるUIパターンなので、覚えておくと非常に便利です。

ステップ1:Android Studioで新規プロジェクトを作成

Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な項目をすべて入力のうえ新しいプロジェクトを作成します。

ステップ2:レイアウトファイル(activity_main.xml)にコードを追加

res/layout/activity_main.xml を開き、以下のコードを記述します。SwipeRefreshLayoutの中にTextViewを配置するシンプルな構成です。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Swipe to Reload"
            android:textColor="@android:color/background_dark"
            android:textSize="24sp"
            android:textStyle="bold" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>

ステップ3:MainActivity.kt にリフレッシュ処理を実装

src/MainActivity.kt に以下のコードを追加します。スワイプを検知するとカウンターが増加し、約4秒後にローディングインジケーターが自動的に消える仕組みです。

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

class MainActivity : AppCompatActivity() {

    lateinit var swipeRefreshLayout: SwipeRefreshLayout
    lateinit var textView: TextView
    var number: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        swipeRefreshLayout = findViewById(R.id.swipe)
        textView = findViewById(R.id.textView)

        swipeRefreshLayout.setOnRefreshListener {
            number++
            textView.text = " Total number = $number"
            Handler().postDelayed(Runnable {
                swipeRefreshLayout.isRefreshing = false
            }, 4000)
        }
    }
}

補足:引数なしの Handler() コンストラクタは API 30 以降で非推奨となっています。最新の環境では Handler(Looper.getMainLooper()) を使用することが推奨されます。

ステップ4:AndroidManifest.xml を確認・編集

androidManifest.xml に以下のコードを追加(または内容を確認)します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

依存関係の追加について

プロジェクトによっては、app/build.gradle の dependencies ブロックに以下のライブラリが必要です。最近のAndroid Studioのテンプレートには含まれていることが多いですが、クラスが見つからないというエラーが出る場合は追加してください。

implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

アプリを実行して動作を確認しよう

それではアプリを実行してみましょう。ここでは、実機のAndroidスマートフォンがPCに接続されているものとして説明を進めます。

Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーにある実行アイコン(Run)KotlinでAndroidにスワイプリフレッシュレイアウト(SwipeRefreshLayout)を実装する方法 をクリックします。候補が表示されたら自分のモバイル端末を選択してください。しばらくすると、端末にアプリの初期画面が表示されます。

画面を下にスワイプすると円形のインジケーターが回転し、「Total number」の数値が更新されれば実装成功です。

KotlinでAndroidにスワイプリフレッシュレイアウト(SwipeRefreshLayout)を実装する方法

KotlinでAndroidにスワイプリフレッシュレイアウト(SwipeRefreshLayout)を実装する方法

  1. AndroidアプリでGridViewレイアウトを作成する方法をステップ解説

    はじめに本記事では、AndroidアプリでGridViewレイアウトを実装する方法を、サンプルコードとともにステップバイステップで解説します。GridViewを使うと、画像やテキストなどの要素をグリッド状(格子状)に並べて表示できるため、ギャラリー画面やメニュー画面など、さまざまな場面で活用できます。実装手順ステップ1:新規プロジェクトの作成Android Studioを起動し、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力して、プロジェクトのセットアップを完了させてください。ステップ2:activity_main.xmlの編集res/

  2. 【Android】TabLayoutを使ってタブレイアウトを作成する方法を徹底解説

    この記事では、Androidアプリでタブレイアウト(TabLayout)を作成する方法を、実際のサンプルコードとともに段階的に解説します。TabLayoutとViewPagerを組み合わせることで、指でスワイプしながら画面を切り替えられる、直感的なタブ型UIを簡単に実装できます。手順1:Android Studioで新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。手順2:依存関係(Dependency)を追加するタブレイアウトを使用するために、