SwipePalletView を OSSで公開した。
こんな感じでちょっとスワイプしたら端っこまで自動で移動するようなViewだ。
使い方とかは上記サイトを見ていただくとして、今回は androidで初めてカスタムビューを作ったので、その作り方的なのを書いてみる。
カスタムビューの基本
まずは、RelativeLayout などのViewを継承したクラスを作る。そのあとに各Viewで必要なコンストラクタを定義。
class CustomView extends RelativeLayout { public SwipePalletView(Context context) { super(context); init(null); } public SwipePalletView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public SwipePalletView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private void init(AttributeSet attrs) { if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SwipePalletView); float scale = a.getFloat(R.styleable.SwipePalletView_widthScale, 0.5f); int duration = a.getInteger(R.styleable.SwipePalletView_horizontalDuration, 500); a.recycle(); } } }
このattr
は、レイアウトXMLで定義した属性値が入っている。
Styleable
res/attrs.xml
を作成する。
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="SwipePalletView"> <attr name="widthScale" format="float" /> <attr name="horizontalDuration" format="integer" /> </declare-styleable> </resources>
こうすることで、以下のようにXMLに属性を追加できる。
<com.honkimi.swipepalletview.SwipePalletVerticalView custom:heightScale="0.3" custom:verticalDuration="700" android:layout_width="match_parent" android:layout_height="wrap_content"> </com.honkimi.swipepalletview.SwipePalletVerticalView>
attr の format
は色々な形式で指定できる。
Viewの作成
後はそれぞれ独自のViewの挙動を作ってあげればいい。
TODO
build.gradle で compile 'com.github.traex.rippleeffect:library:1.2.3'
みたいな指定でビルドできるようにしたいが、何かよくわからなかったのでできなかった。時間あるときにまたチャレンジしてみよう。