【Android Tips】androidのボタンアニメーションをちらつかせずに実装する
こんにちは、andyです。
今回はandroidのネタです。
最近androidのプログラミングはご無沙汰してましたので、忘れてしまっていることも多いのですが思い出しながら書きたいと思います。
以前にandroidのButtonオブジェクトをAnimationを使って移動させたときにボタンが反応しなくなったことがありました。
この問題は、ButtonオブジェクトのLayoutParamがアニメーション後に変更されず、元の位置のままのために起こるようで、アニメーション後にLayoutParamを変更するとボタンは反応するようになります。
ただ、この方法を行うと、アニメーション実行後にいったんオブジェクトが非表示になるために、画面がちらつきます。そのために、どうしたら良いのかと考えておりました。
実際のコードはこちらの様な感じです。
先日、ふと思い出して何か他の方法がないか調べておりましたところ、3.0以降にObjectAnimatorというクラスがあり、そのクラスを使うと簡単に実現できることがわかりましたので、忘れないように書いておきたいと思います。
コード
コードはこんな感じです。
まずレイアウトファイルから。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <FrameLayout android:id="@+id/frame" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="58dp" android:layout_marginTop="28dp" android:background="#0000ff" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="87dp" android:text="Button" /> </FrameLayout> </RelativeLayout>
次にプログラムコードです。
import android.os.Bundle; import android.animation.ObjectAnimator; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; public class MainActivity extends Activity implements OnClickListener { private Button btn; private FrameLayout frame; private float movePosY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) this.findViewById(R.id.button1); btn.setOnClickListener(this); frame = (FrameLayout)this.findViewById(R.id.frame); movePosY = frame.getY(); } @Override public void onClick(View arg0) { movePosY += 100; ObjectAnimator mover = ObjectAnimator.ofFloat(frame, "translationY", movePosY); mover.start(); } }
非常に簡単なコードで実現できてしまうため、あの時は何だったのだろうと思ってしまいました。
今回のコードでは、恐らく複数のボタンを同時に移動させたりといったことがカスタムGUIで必要になると思いましたので、テストのためにボタンをFrameLayoutにいれ、ボタンクリックと同時にFrameLayoutをアニメーションさせています。また、アニメーション後のポジションから次のアニメーションが行われるようにしています。
ぜひ使ってみてください。それでは。
コメントをどうぞ