随便点击View中的任何位置,都会启动一个动画效果成圆形慢慢扩充全屏,要实现这个效果首先我们先要自定义一个View,在View中监听到我们手指点击的位置,在根据这个位置启动一个动画,
代码如下:
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
@SuppressLint("NewApi")
public class lightView extends View {
private ObjectAnimator ainm1;
private float progress;
private int x;
private int y;
private int x1;
private int y1;
private int director;
private int colors;
private Paint paint;
public lightView(Context context) {
super(context);
}
//实现在布局文件中使用
public lightView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//属性动画
ainm1 = ObjectAnimator.ofFloat(this, "progress", 0, 1).setDuration(500);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(colors);
if (y < getHeight() / 2 && x > getWidth() / 2) {
y1 = getHeight() - y;
director = (int) Math.sqrt(x * x + y1 * y1);
}
if (x < getWidth() / 2 && y > getHeight() / 2) {
x1 = getWidth() - x;
director = (int) Math.sqrt(x1 * x1 + y * y);
}
if (x < getWidth() / 2 && y < getHeight() / 2) {
y1 = getHeight() - y;
x1 = getWidth() - x;
director = (int) Math.sqrt(x1 * x1 + y1 * y1);
}
if (x > getWidth() / 2 && y > getHeight() / 2) {
director = (int) Math.sqrt(x * x + y * y);
}
float r = progress * director;
//画圆
canvas.drawCircle(x, y, r, paint);
}
public void setProgress(float progress) {
this.progress = progress;
postInvalidate();
}
//获取点击的位置
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
x = (int) event.getX();
y = (int) event.getY();
ainm1.start();
break;
}
return true;
}
}
如果要想点击其他控件来实现背景变色,首先要用RelativeLayout布局,把我们自定义这个View放在其他布局后面,然后把onTouchEvent这个方法屏蔽掉,加上下面两个方法
代码如下:
public void setColor(int color){
colors = color;
}
public void start(int width, int height){
x = width;
y = height;
ainm1.start();
}
具体调用如下:
我这里是在gridView中点击其中的每一项会有不同的颜色
gridView.setOnItemClickListener(new OnItemClickListener() {// 颜色选择
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//获取点击按钮在屏幕中的具体位置,local[0]为宽,local[1]为高
int[] local = new int[2];
view.getLocationInWindow(local);
lightView.setColor(colors[position]);
lightView.start(local[0] + view.getWidth() / 2, local[1]);
}
});