kuwa_38です。先日SQLiteを使ったAndroidアプリを作成していたのですが、表示データが多くなると画面外に表示されるため対策が必要だなと考えていました。
この記事ではScrollView
を使って特定領域内をスクロール可能にする方法をご紹介します。
今回作成するアプリと過去の記事
今回ScrollView
によりスクロールを導入するアプリを紹介します。簡単に言うとSQLiteを用いてDB内のデータを表示するアプリです。今回はそのアプリで表示するViewにスクロール機能をつけることがゴールです。
qiita.com
画面レイアウト用のxmlにおいて、スクロールをさせたい範囲をScrollView
で囲むと、その範囲をスクロールさせることができます。
<ScrollView
androidlayout_width="match_parent"
androidlayout_height="match_parent"
androidlayout_marginTop="200dp"
androidid="@+id/scrollView">
<TextView
androidid="@+id/text_view"
androidlayout_width="wrap_content"
androidlayout_height="wrap_content"
androidtext="「表示」を押すとDBのデータを全件表示します" />
</ScrollView>
(注意1)画面のレイアウトが崩れる
「ScrollView
で要素を囲む」。これだけでいいのですが、注意点があります。1つは画面のレイアウトが崩れることがあることです。文字入力しようとするとキーボードが出てきた際にレイアウトが崩れてしまいます。
注意1の解決方法
ScrollView
にandroid:isScrollContainer="false"
を追加することで解決できます。下記のサイトによると
isScrollContainer
はIMEが表示されたときにスペースを空けるためにViewをリサイズするかどうかを指定するものだそうです。
<ScrollView
androidlayout_width="match_parent"
androidlayout_height="match_parent"
androidlayout_marginTop="200dp"
androidisScrollContainer="false"
androidid="@+id/scrollView">
<TextView
androidid="@+id/text_view"
androidlayout_width="wrap_content"
androidlayout_height="wrap_content"
androidtext="「表示」を押すとDBのデータを全件表示します" />
</ScrollView>
retrocatsoft.blogspot.com
(注意2)複数要素を指定したい場合
2つ目はScrollView
は1つの要素しか指定できないことです。
実際、下記のように要素を追加すると、エラーが発生します。
<ScrollView
androidlayout_width="match_parent"
androidlayout_height="match_parent"
androidlayout_marginTop="200dp"
androidisScrollContainer="false"
androidid="@+id/scrollView">
<TextView
androidid="@+id/text_view"
androidlayout_width="wrap_content"
androidlayout_height="wrap_content"
androidtext="「表示」を押すとDBのデータを全件表示します" />
<TextView
androidid="@+id/textView2"
androidlayout_width="wrap_content"
androidlayout_height="wrap_content"
androidtext="2つ目のTextView" />
</ScrollView>
# consoleのエラー
...(略)
...ScrollView can host only one direct child
注意2の解決方法
LinearLayout
で指定したい要素を囲みScrollView
で指定する要素をLinearLayout
の要素1つとすることで解決できます。
<ScrollView
androidlayout_width="match_parent"
androidlayout_height="match_parent"
androidlayout_marginTop="200dp"
androidisScrollContainer="false"
androidid="@+id/scrollView">
<LinearLayout
androidid="@+id/LinearLayout"
androidorientation="vertical"
androidlayout_height="fill_parent"
androidlayout_width="fill_parent">
<TextView
androidid="@+id/text_view"
androidlayout_width="wrap_content"
androidlayout_height="wrap_content"
androidtext="「表示」を押すとDBのデータを全件表示します" />
<TextView
androidid="@+id/textView2"
androidlayout_width="wrap_content"
androidlayout_height="wrap_content"
androidtext="2つ目のTextView" />
</LinearLayout>
</ScrollView>
おわりに
今回はScrollView
を使って特定領域をスクロールさせる方法をご紹介しました。最初はScrollView
で囲むだけなので簡単だと思っていましたが、レイアウト崩れや要素の制限などやってみると思いの他詰まり奥が深い(というか自分が知らないことが多い)なという印象です。
今後もAndroidアプリ開発は続けるつもりなのでこういった記事を書いていこうと思います。
◆TECH PLAY
techplay.jp
◆connpass
rakus.connpass.com