1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > android自定义控件(组合控件)相关

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

时间:2021-05-28 17:41:03

相关推荐

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、外部接口:为内部组件设置事件监听时,若有需要,则自定义接口,暴露给控件使用者

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。