RealViewSwitcherを作りました

Android Advent Calendar

このエントリはAndroid Advent Calendarのエントリの1つです。
クリスマスまでに1日1記事更新されるので、ぜひご覧になってください。

Android Advent Calendar http://androidadvent.blogspot.com/

RealViewSwitcherを作りました

Launcherアプリのように、1ページごとに切り替わるViewGroupを作りました。
すでにcompatibility packageでViewPagerが公開されていますが
これを作った当時は、まだcompatibility packageがありませんでした。
RealViewSwitcherというViewGroupです。
"RealViewSwitcher"で検索すると同じようなクラスがでてきますが、私に命名センスがないので名前だけ拝借しました。

すでにデコ美シンプルQRコードにインプリされています。

動画


3つページがあり、ぐるぐる循環します。



もちろんフリックする以外にコントロールを追加することが可能です。



ばいーんの挙動を変更することも可能です。

簡単な使い方

コードから動的にViewの追加も可能ですが、xmlにも記述できます。
通常の独自Viewと同じやり方です。

<?xml version="1.0" encoding="utf-8"?>
<view xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res/jp.tomorrowkey.android.realviewswitchersample"
  android:id="@+id/viewSwitcher"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  class="jp.tomorrowkey.android.realviewswitcher.widget.RealViewSwitcher"
  app:interpolator="overshoot_interpolator" >

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color1"
    android:gravity="center"
    android:text="1"
    android:textSize="64sp" />

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color2"
    android:gravity="center"
    android:text="2"
    android:textSize="64sp" />

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color3"
    android:gravity="center"
    android:text="3"
    android:textSize="64sp" />
</view>

ばいーんの挙動を変更したい場合に限り、

xmlns:app="http://schemas.android.com/apk/res/使用するアプリのパッケージ名"

app:interpolator="overshoot_interpolator"

が必要です。
interpolatorに設定可能なリストはここに定義されています。

RealViewSwitcher/res/values/attrs.xml at master from tomorrowkey/RealViewSwitcher - GitHub 
https://github.com/tomorrowkey/RealViewSwitcher/blob/master/RealViewSwitcher/res/values/attrs.xml

注意点

人によってフリックするときの感覚が違うと思うので、閾値の調整が必要です。
ぜひ、コードを読んで調整してみてください。

最後に

初めてViewGroupを書いてみて、Androidの描画の仕組みについて理解が深まりました。
Androidの独自Viewは大変だけど楽しいですね。