Android所有的UI都是繼承自View類,所以要實現自己的組件,我們只要繼承View類然後重寫業務需要的辦法就行了
常用重寫的辦法有:
以下是一個實現了跟隨觸點的小球自定義組件。
public class newUI extends View {
private float cx,cy;
private Paint paint = new Paint();
public newUI(Context context) {
super(context);
}
public newUI(Context context,AttributeSet set){
super(context, set);
}
protected void onDraw (Canvas canvas){
//super.onDraw(canvas);
paint.setColor(Color.RED);
canvas.drawCircle(cx, cy, 20, paint);
}
public boolean onTouchEvent (MotionEvent event){
cx = event.getX();
cy = event.getY();
invalidate();
return true;
}
}
跟平常的組件一樣,我們可以用代碼或是XML文件來調用
代碼調用
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.a);
LinearLayout tt =new LinearLayout(this);
newUI nn = new newUI(this);
tt.addView(nn);
setContentView(tt);
}
XML調用
<com.example.newui.newUI
android:layout_width="match_parent"
android:layout_height="match_parent"
/>