自定view(一)

      Android App中,所有的用户界面元素都是由View和ViewGroup的对象构成的,View是绘制在屏幕上的用户能与之交互的一个对象。很多时候android原生的控件不能满足我们的需求,这时我们往往需要自定义控件。自定义控件做法:继承View或继承View的子类(TextView、ImageView......)。

     

       简单的自定义View实现:

              一、编写一个类继承View

              二、在布局中使用自定义的类

                   

/**
 * 自定义简单的View:画一个矩形形按键
 * @author rongyun
 */
public class CustomView extends View{
	private Paint paint;
	public CustomView(Context context) {
		super(context);
	}
	public CustomView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		//画笔
		paint = new Paint();
		paint.setColor(Color.GREEN);
		//画矩形
		RectF rectF=new RectF();
		rectF.set(10, 10, 300, 200);
		canvas.drawRect(rectF, paint);
	}
}

                   

   
   
    
    
    
    
    
    

   
   

       自定义View高级应用

             一、编写自己的attrs.xml文件,定义自己的属性

             二、继承View,实现attrs.xml定义的属性

             三、布局文件中使用自定义的控件
                   


  
  

  
  
    
   
   
       
    
    
       
    
    
   
   
   

  
  

                   
public class CustomView extends View {

	private Integer downcolor;
	private Integer upcolor;
	private Paint paint;
	private Integer color;

	public CustomView(Context context) {
		super(context);
	}

	public CustomView(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray typedArray = context.obtainStyledAttributes(attrs,
				R.styleable.PieChart, 0, 0);
		try {
			//设置默认颜色
			downcolor = typedArray.getColor(R.styleable.PieChart_downcolor,
					Color.BLUE);
			upcolor = typedArray.getColor(R.styleable.PieChart_upcolor,
					Color.GREEN);
		} catch (Exception e) {
			Log.e("log", "error");
		} finally {
			typedArray.recycle();
		}
		paint = new Paint();
		color = upcolor;
	}

	public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		paint.setColor(color);
		canvas.drawCircle(getWidth() / 2, (getHeight() / 2),
				((getHeight() / 2) - 1), paint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int i = event.getAction();
		switch (i) {
		case MotionEvent.ACTION_DOWN:
			color = downcolor;
			break;
		case MotionEvent.ACTION_UP:
			color = upcolor;
			break;
		}
		invalidate();
		return super.onTouchEvent(event);
	}
}
     
                   

   
   
    
    
    

   
   



            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值