10
11

More than 5 years have passed since last update.

ScrollViewを持ったAlertDialogを表示する

Posted at

はじめに

利用規約画面などの文章を見せるためだけの画面を作成する際に、ActivityやFragmentで一画面作るのが正攻法だとは思います。
しかし如何せん面倒なのでもう少しライトに使えるAlearDialogでサクッと作った際の自分向けメモを残しておきます。

実装方法

まずはScrollViewを持つレイアウトファイルを作成します。
今回は要素として複数個のTextViewを持つためLinearLayoutを挟んでいますが、もっと手抜きをするならScrollView直下にTextViewをそのまま入れてしまっても大丈夫です。

view_scrollable_text.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hoge" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="fuga" />
    </LinearLayout>
</ScrollView>

あとは任意のタイミングでAlertDialogを表示するだけです。
このときsetMessageはせず、上記で定義したレイアウトファイルをsetViewします。
※ここではMainActivityのonCreateで表示するものとします。

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    AlertDialog.Builder(applicationContext)
        .setTitle("title")
        .setView(R.layout.view_scrollable_text)
        .setPositiveButton(
            "OK"
        ) { _, _ ->
            // Do nothing
        }
        .show()
}

使用例

image.png

おわりに

枝葉に時間をかけすぎるのも辛いので適度に手を抜いていきましょう。

10
11
0

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
10
11