標籤:
* 做Android應用開發想深入的話 就是要會使用一些進階控制項,以及自訂View了,好吧,開始自訂view走向大神之路,這一節從最簡單的
* 圓形view開始,如何定義屬性,以及回調使用。
下面是實現代碼
/** * 一個圓形的進度條控制項 * @author fengy * */public class CustomProgressView extends View {Paint paint ;int mColor;//圓的顏色private OnClickProgressViewListener mclickProgressView;public CustomProgressView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stubpaint = new Paint();TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.customprogress);mColor = typedArray.getColor(R.styleable.customprogress_color, Color.RED);typedArray.recycle();}@Overrideprotected void onDraw(Canvas canvas) {// TODO Auto-generated method stubsuper.onDraw(canvas);//畫最外層的圓paint.setColor(mColor);paint.setStyle(Style.STROKE);canvas.drawCircle(getWidth()/2, getHeight()/2, getWidth()/2, paint);}public void setLisner(OnClickProgressViewListener pOnClickProgressView) {mclickProgressView = pOnClickProgressView;}@Overridepublic boolean onTouchEvent(MotionEvent event) {// TODO Auto-generated method stubif (event.getAction()==MotionEvent.ACTION_UP) {mclickProgressView.onClick(CustomProgressView.this);}return super.onTouchEvent(event);}/* * 暴露介面 作為回調使用 * */public interface OnClickProgressViewListener {public void onClick(CustomProgressView v);}}為什麼使用回調呢,目的是為了view 的通用性,商務邏輯讓使用者去實現。
有兩種方法使用回調第一種
CustomProgressView cView = (CustomProgressView) rootView.findViewById(R.id.cv); cView.setLisner(new OnClickProgressViewListener() {@Overridepublic void onClick(CustomProgressView v) {// TODO Auto-generated method stub//dosomething}});
第二種讓你的類實現 點擊介面implements OnClickProgressViewListener 然後實現他的onclick方法,
誰用誰實現是不是非常簡單呢,Android的view中都是使用的這種方式,就是牛逼的觀察者模式。
自訂介面之圓-自訂屬性回調介面