Android模拟下雨效果

2016-11-10  本文已影响435人  BlackNeko

使用RippleDrawable和模拟屏幕点击实现下雨时水波纹效果。

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_drawable"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="amorypepelu.github.io.drawabledemo.DrawableActivity">

    <Button
        android:id="@+id/RippleDrawableBtn"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/ripple"
        android:text="" />
</LinearLayout>

Drawable:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@android:color/holo_purple"></ripple>

java代码:

private int width;
private int height;
private Random random;

random = new Random();
width = getResources().getDisplayMetrics().widthPixels;
height = getResources().getDisplayMetrics().heightPixels;

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        int x = (int) random.nextLong() % width;
        int y = (int) random.nextLong() % height;
        clickEvent(x, y);
        sendEmptyMessageDelayed(0, 600);
    }
};
handler.sendEmptyMessage(0);
handler.sendEmptyMessageDelayed(0,200);
handler.sendEmptyMessageDelayed(0,400);

模拟点击事件:

private void clickEvent(int x, int y) {
    long downTime = SystemClock.uptimeMillis();
    MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
            MotionEvent.ACTION_DOWN, x, y, 0);
    MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
            MotionEvent.ACTION_UP, x, y, 0);
    mRippleDrawableBtn.onTouchEvent(downEvent);
    mRippleDrawableBtn.onTouchEvent(upEvent);
    downEvent.recycle();
    upEvent.recycle();
}

参考:

Drawable家族的前世今生

Android模拟点击的四种方式

上一篇 下一篇

猜你喜欢

热点阅读