如何自定义自己的VIEW

来源:互联网 发布:淘宝店怎么做广告 编辑:程序博客网 时间:2024/05/29 04:47

1.继承VIew类

View(Context context)
Simple constructor to use when creating a view from code. //从代码中加载时会调用


View(Context context, AttributeSet attrs)
Constructor that is called when inflating a view from XML. //从XML中加载时会调用


View(Context context, AttributeSet attrs, int defStyleAttr)
Perform inflation from XML and apply a class-specific base style. //inflation 加载时会调用

所以要根据自己的需求实现父类的构造方法


2.重写onDraw(非必须,如果你想让界面初始化的时候显示一些东西,可以在此方法内绘制)


简单示例:随手指移动的小球 

public class DrawCircel extends View {private Paint paint = new Paint();private float x = 10;private float y = 10;// 保证此view可以从代码中加载public DrawCircel(Context context) {super(context);}// 保证此view可以从XML中加载public DrawCircel(Context context, AttributeSet set) {super(context, set);}// 绘制内容时调用@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);paint.setColor(Color.RED);canvas.drawCircle(x, y, 10, paint);}// 位该View的触碰编写事件@Overridepublic boolean onTouchEvent(MotionEvent event) {x = event.getX();y = event.getY();invalidate();// 通知View重绘,会调用onDraw方法return true;}}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <com.example.movecircle.DrawCircel        android:layout_width="wrap_content"        android:layout_height="wrap_content" >    </com.example.movecircle.DrawCircel></RelativeLayout>


1 0