Dialog を使ってスプラッシュ画面を作りました。
あとなんかカッコいいと思ってメソッドチェーンにしてみた。
コード
SplashScreen.java
public class SplashScreen {
private static final String TAG = "SplashScreen";
public interface OnStateChangeListener {
void onFinish();
void onFinished();
}
public static class Builder {
private Context mContext;
private View mView;
private int mLayoutResId;
private long mDuration;
private int mFinishAnimationResId;
private OnStateChangeListener mListener;
public Builder with(Context context) {
mContext = context;
return this;
}
public Builder setView(View view) {
mView = view;
return this;
}
public Builder setView(int resId) {
mLayoutResId = resId;
return this;
}
public Builder setDuration(long duration) {
mDuration = duration;
return this;
}
public Builder setFinishAnimation(int resId) {
mFinishAnimationResId = resId;
return this;
}
public Builder setOnStateChangeListener(OnStateChangeListener listener) {
mListener = listener;
return this;
}
public Dialog create() {
if (mLayoutResId != 0) {
mView = LayoutInflater.from(mContext).inflate(mLayoutResId, null, false);
}
if (mView == null) {
Log.e(TAG, "View is empty.");
return null;
}
int styleId;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
styleId = android.R.style.Theme_DeviceDefault_NoActionBar_TranslucentDecor;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
styleId = android.R.style.Theme_DeviceDefault_NoActionBar;
} else {
styleId = android.R.style.Theme_NoTitleBar;
}
Dialog dialog = new Dialog(mContext, styleId);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(false);
dialog.setContentView(mView);
return dialog;
}
public void start() {
final Dialog dialog = create();
if (dialog == null) {
Log.e(TAG, "Failed to create splash.");
return;
}
dialog.show();
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
Animation anim = AnimationUtils.loadAnimation(mContext, mFinishAnimationResId);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
dialog.dismiss();
mListener.onFinished();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mView.startAnimation(anim);
mListener.onFinish();
}
}, mDuration);
}
}
}
使い方
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
new SplashScreen.Builder().with(this)
.setView(R.layout.splash)
.setDuration(2000)
.setFinishAnimation(android.R.anim.fade_out)
.setOnStateChangeListener(new SplashScreen.OnStateChangeListener() {
@Override
public void onFinish() {
mTextView.setText("onFinish()");
}
@Override
public void onFinished() {
mTextView.setText("onFinished()");
}
}).start();
}
...
スプラッシュ表示中の画面回転のことは考えていません。
すいません。
(ところで Handler は中で new するよりもメンバ変数として静的に定義しておいた方が良いのでしょうか…?)