`
SLFly
  • 浏览: 422 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

自定义View的实现方法

阅读更多
当开发者打算派生自定义的 UI 组件时,首先定义一个继承 View 基类的子类,然后重写 View 类的一个或多个方法即可。
通常可以被用户重写的方法如下:
构造器 :重写构造器是定制 View 的最基本方式。当 Java 代码创建一个 View 实例,或根据 XML 布局文件加载并构造界面时将需要调用该构造器。
onFinishlnflate() :这是一个回调方法。当应用从 XML 布局文件加载该组件并利用它来构建界面之后,该方法将会被回调。
onMeasure(int, int) :调用该方法来检测 View 组件及它所包含的所有子组件的大小。
onLayout(boolean, int, int, int, int) :当该组件需要分配其子组件的位置、大小时,该方法就会被回调。
onSizeChanged(int, int, int, int) :当组件的大小被改变时回调该方法。
onDraw(Canvas) :当该组件将要绘制它的内容时回调该方法进行绘制。
onKeyDown(int, KeyEvent) :当某个键被按下时触发该方法。
onKeyUp(int, KeyEvent) :当松开某个键时触发该方法。
onTrackballEvent(MotionEvent) :当发生轨迹球事件时触发该方法。
onTouchEvent(MotionEvent) :当发生触摸屏事件时触发该方法。
onWindowFocusChanged(boolean) :当该组件得到或失去焦点时触发该方法。
onAttachedToWindow() :当把该组件放入某个窗口时触发该方法。
onDetachedFromWindow() :当把该组件从某个窗口分离时触发该方法。
onWindowVisibilityChanged(int) :当包含该组件的窗口的可见性发生改变时触发该方法。
以上方法不需要全部重写,根据业务需要重写部分即可。

当在XML文件中管理自定义组件时,出了继承View,还要重写View的两个构造器,一个不带参数的,例如,
	public DrawView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}
	public DrawView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}


可以有两种方式实现

第一种,在XML文件中管理组件,这种方法必须要重写带参数的构造器
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LinearLayout root  = (LinearLayout) findViewById(R.id.root);
		final DrawView draw = new DrawView(this);
		draw.setMinimumHeight(300);
		draw.setMinimumWidth(500);
		root.addView(draw);
	}



第二种,在Activity中将组件添加到布局中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/root" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <com.SLFly.crazyit_02_customview.DrawView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics