android自定义控件(二) 入门,继承View

本文详细介绍了如何在Android中自定义控件,包括View的工作原理、创建View类、增加属性、绘制屏幕、响应用户消息及自定义回调函数。通过实例展示了使用Canvas、Paint和Path进行图形绘制,并提供了布局配置和示例代码。注意,自定义控件在布局中的显示方式需特别关注。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明地址:http://blog.youkuaiyun.com/ethan_xue/article/details/7313788

ps: 可根据apidemo里LableView,list4,list6学习

文档在dev guide/Framework Topics/User Interface/Building Custom Components


自定义控件的步骤:

1 View的工作原理 
2 编写View类 
3 为View类增加属性 
4 绘制屏幕 
5 响应用户消息 
6 自定义回调函数 


不多说,主要是Canvas, Paint, Path

public class CustomView1 extends View {

	private Paint mPaint;
	// private static final String mText = "drawText";
	private String mText = "drawText";

	public CustomView1(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		mPaint = new Paint();
		mPaint.setColor(Color.BLUE);
		// FILL填充, STROKE描边,FILL_AND_STROKE填充和描边
		mPaint.setStyle(Style.FILL);
		canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);// 画一个矩形

		mPaint.setColor(Color.GREEN);
		mPaint.setTextSize(35.0f);
		canvas.drawText(mText, 10, 60, mPaint);
	}

}


布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ethan.customview1.CustomView1  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    />
</LinearLayout>
效果图

注意,此时,在控件下放一个textView的话,是显示不出来的(TextView放在控件上面可以显示),以后再解决

下载地址 http://download.youkuaiyun.com/detail/ethan_xue/4108820


                
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值