android5.0中新增加了material design的按钮样式,今天自定义实现一下按钮的样式风格。
先说一下简单那的思路。
1.首先自定义一个MyButton继承自Button
2.重写onTouchEvent方法,在MotionEvent.ACTION_DOWN中记录用户的点击坐标
3.以该坐标为圆心,画圆,不断重绘让圆的半径不断增大,直到圆的半径大于所点击的组件的宽和高的最大值
MyTextView.java如下
package com.example.android5;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.TextView;
public class MyTextView extends Button {
//circlex,circley用来标识用户点击的坐标和防止用户在当前绘画未完成之前再次点击
private float circlex = -1.0f;
private float circley = -1.0f;
//width,height用来标识点击组件的宽和高
int width;
int height;
Paint paint = new Paint();
int i = 5;
//是否按下
boolean isPress = false;
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
//画笔初始化,注意如果需要在布局文件中引入该view,必须重写该构造方法
int color = Color.argb(127,102,201,98);
paint.setColor(color);
paint.setAntiAlias(true);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
if (MotionEvent.ACTION_DOWN == action) {
if (circlex < 0 && circley < 0) {//如果circlex < 0 && circley < 0成立,表示第一次点击,防止重复点击
circlex = event.getX();
circley = event.getY();
isPress = true;
invalidate();//调用onDraw方法
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
setPadding(10,10,10,10);
width = getWidth();
height = getHeight();
int max = Math.max(height, width);
if (i < max && isPress && circlex > 0 && circley > 0) {//如果圆的半径小于组件宽或高的最大值时候
canvas.drawCircle(circlex, circley, i, paint);
i+= 2;
invalidate();
}else{
i = 0;
circlex = -1;
circley = -1;
isPress = false;
}
}
}
activity_main.xml引用自定义的view:
<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"
tools:context=".MainActivity" >
<com.example.android5.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#8c000000"
android:textColor="#ffffff"
android:layout_centerInParent="true"
android:text="skfdsdjkfsdfasdfasd"
/>
</RelativeLayout>
至此一个自定义的material design的按钮样式已经实现。
源码连接:http://download.csdn.net/detail/mockingbirds/8136523