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"
/>