如何在Android中创建自己的View

在Android中创建自己的VIEW只要继承android.view.View类,然后在onDraw方法中使用canvas画自己所需要的东东就可以了。当然你还需要做一些实际处理,比如对用户点击的处理,向前或向后滚动的处理等。

以下是我创建的CalendarView中,部分显示日历的代码:

public CalendarView(Context context) {
		super(context);

		calendarBrowse = (CalendarBrowse) context;

		setFocusable(true);
		setFocusableInTouchMode(true);

		cPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		cPaint.setStyle(Paint.Style.FILL_AND_STROKE);
		cPaint.setColor(Color.RED);
		cPaint.setTextSize(20f);

		tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
		tPaint.setColor(Color.WHITE);
		tPaint.setTextSize(20f);

		setBackgroundColor(getResources().getColor(R.color.background));

		mGestureDetector = new GestureDetector(
				new GestureDetector.SimpleOnGestureListener() {

					@Override
					public boolean onFling(MotionEvent e1, MotionEvent e2,
							float velocityX, float velocityY) {

						if (e1.getX() > e2.getX()) {
							cal.add(Calendar.MONTH, 1);
							CalendarView.this.invalidate();
						}

						if (e1.getX() < e2.getX()) {
							cal.add(Calendar.MONTH, -1);
							CalendarView.this.invalidate();
						}

						return true;

					}

					@Override
					public boolean onSingleTapUp(MotionEvent e) {
						day = getDay(e.getX(), e.getY());
						if (day != INVALID_POSITION) {
							calendarBrowse.showTimeItemList(year, month, day);
						}
						return true;
					}

				});
	}
 

GestureDetector类是用于对手势操作的处理,它可以截取你对屏幕的单击,长按,
向前向后滚动等操作,这个功能在Android的框架中封装的很好,使用起来很舒服。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>