android自定义控件(组合控件)相关

自定义组件及根据需求定义符合要求的控件

自定义控件流程:

一、继承相应View,如:TextView  ImageView; 组合控件一般继承ViewGroup,如:LinearLayout etc.

二、构造方法:

		public ArrowIndicatorView(Context context){this(context, null);}	//该构造方法在代码中new该控件时调用
		public ArrowIndicatorView(Context context, @Nullable AttributeSet attrs) {
    			this(context, attrs, 0);
		}
		public ArrowIndicatorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    			super(context, attrs, defStyleAttr);
		}
后两个构造方法是在xml文件中使用该控件时调用。
		1、构造方法相关参数:
			context:一般获取的是Activity;
			AttributeSet:与XML文档中的标签相关联的属性集合,指android系统提供的属性??
			int defStyleAttr:定义的风格属性??该属性一般用不到
	三、自定义该控件的属性:如尺寸大小等,用于在xml文件中控制该控件(耦合度??)
	(这一步不是必须的,若无自定义属性,就不用这一步)
		1、在res/values/路径下,新建attrs.xml文件(若无此文件)
		2、在declare-styleable标签下定义控件属性:		
			<declare-styleable name="ArrowIndicatorView">
    				<attr name="triangleHeight" format="dimension"/>
			</declare-styleable>	
			第一个name为自定义的控件名称
			<attr 后的name为属性名,format为属性类型
		3、在控件类中取得自定义属性:
			TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ArrowIndicatorView);
			Drawable bg_tab = array.getDrawable(R.styleable.ArrowIndicatorView_tabsBackground);
			array.recycle();

使用TypeArray获取自定义属性,obtainStyledAttributes的第二个属性为attrs.xml文件中定义的name?

获取属性用 array.getAttrbuteName()方法

TypeArray使用完毕后,必须调用recycle()方法回收TypeArray,为给下一调用者使用??

四、 组合控件,添加组件有两种方式:

1、首先new相应控件,并设置必要属性,最后使用addView()向ViewGroup内部添加组件

eg:

			View view = new View(getContext());
			LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) triangleHeight);
			view.setLayoutParams(params);
			addView(view);

2、获取自定义属性时使用方法:obtainStyledAttributes(@StyleRes int resid, int[]attrs)

第一个参数为:layout.xml文件的Id,第二个属性为attrs.xml文件中定义的name?

五、横竖屏时的保存和恢复数据(若需要)

1、保存数据重载(??)onSaveInstanceState()方法

2、恢复数据重载onRestoreInstanceState(Parcelable state)方法

六、自定义View时,用到的方法可能有:

1、onMeasure 测量尺寸

2、onLayout 在View中的位置?

3、onDraw 最常用到

七、若有其他需要,可复写相应方法,涉及到的点有:

1、事件分发机制:拦截相应事件

2、外部接口:为内部组件设置事件监听时,若有需要,则自定义接口,暴露给控件使用者



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值