android开发中,为了显示效果,大部分控件可能需要重新开发,一般来讲大部分自定义控件可以通过继承自一个android自身控件,重写ondraw来实现。
下面就以开发一个自定义的颜色渐变button为例,说明如果开发自定义控件。
自定义button的CButton.java
package Test.wangfu.controls;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
public class CButton extends View {
??? private int type = 0;??? //定义一个类属性,可以用于在程序中指定,button的样式是矩形还是圆形,这样定义的属性
??? //在xml中引用的时候,引用不到这个属性
??? public CButton(Context context, AttributeSet attrs) {
??? ??? super(context, attrs);
??????? this.type=attrs.getAttributeIntValue(null, "type", 0);??? //获取main.xml的cbutton定义的type属性值
??? }
??? public int getType() {
??? ??? return type;
??? }
??? public void setType(int type) {
??? ??? this.type = type;
??? ??? this.invalidate();?? //更新区域
??? }
??? @Override
??? protected void onDraw(Canvas canvas) {
??? ??? // TODO Auto-generated method stub
??? ??? super.onDraw(canvas);
??? ??? Paint paint = new Paint();
??? ??? // 消除锯齿
??? ??? paint.setAntiAlias(true);
??????? //设置为实心
??? ??? paint.setStyle(Style.FILL);
??????? //设置过滤渐变颜色
??? ??? Shader shader = new android.graphics.LinearGradient(0, 0, 100, 100,
??? ??? ??? ??? new int[] { Color.YELLOW, Color.BLUE, Color.RED }, null,
??? ??? ??? ??? Shader.TileMode.REPEAT);
??? ??? paint.setShader(shader);
?????? //如果等于0,绘一个圆形
??? ??? if (this.getType() == 0) {
??? ??? ??? canvas.drawCircle(30, 30, 30, paint);
??? ??? }
??? ??? else
??? ??? {
??? ??? ??? Rect r=new Rect();
??? ??? ??? r.set(0, 0, 60, 60);
??? ??? ??? canvas.drawRect(r, paint);
??? ??? }
??? }
}
?
main.xml中添加控件
<Test.wangfu.controls.CButton
???????? android:id="@+id/cbutton1"?
???????? android:layout_width="wrap_content"??????????
???????? android:layout_height="100px"???????
???????? type="1"
??? />
?
//在程序中修改自定义的type属性
final Test.wangfu.controls.CButton cbutton=(CButton)this.findViewById(R.id.cbutton1);
cbutton.setOnClickListener(new OnClickListener() {
?? ??? ??? ?public void onClick(View v) {
?? ??? ??? ??? ?// TODO Auto-generated method stub
?? ??? ??? ??? ?if (cbutton.getType() == 0) {
?? ??? ??? ??? ??? ?cbutton.setType(1);
?? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ?cbutton.setType(0);
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?});
?
上面一个可以有两种展示状态的自定义button控件就基本完成了。
?