一、自绘控件
自绘控件主要是通过继承View,然后重写onDraw()方法,绘制逻辑在onDraw中调用即可,如果需要注册事件,只需要实现相关事件监听接口即可(比如OnClickListener);还有就是在自绘控件中如果需要重绘控件,只需要调用invalidate方法即可;在xml布局中使用只需要按普通控件使用即可。
public class MyView extends View implements OnClickListener {
public MyView (Context context, AttributeSet attrs) {
super(context, attrs);
setOnClickListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//实现绘制逻辑
}
@Override
public void onClick(View v) {
//执行相应逻辑,然后重绘view
invalidate();
}
}
二、组合控件
组合控件就是指我们不需要自己实现绘制view的逻辑,使用原生安卓控件来组合出我们需要的界面view。如果组件需要自定义属性,还可以结合TypedArray类和attr.xml中的<declare-styleable>来满足需求。
public class TitleView extends FrameLayout {
private Button leftButton;
private TextView titleText;
public TitleView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this); //加载组合好的布局文件
titleText = (TextView) findViewById(R.id.title_text);
leftButton = (Button) findViewById(R.id.button_left);
leftButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
}
public void setTitleText(String text) {
titleText.setText(text);
}
public void setLeftButtonText(String text) {
leftButton.setText(text);
}
public void setLeftButtonListener(OnClickListener l) {
leftButton.setOnClickListener(l);
}
}
三、继承控件
继承控件就是指现有原生安卓控件不能满足我们需求时,但是我们只需要在原有的安卓控件做些扩展功能即可满足需求时,我们就通过继承的方式来定义控件。
public class EButtonComponent extends Button {
public EButtonComponent(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init(context, attrs);
}
public EButtonComponent(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
// 设置默认按钮背景资源
this.setBackgroundResource(R.drawable.button_search);
// 获得自定义属性
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.EButtonComponent);
int count = ta.getIndexCount();
for (int i = 0; i < count; i++) {
int itemId = ta.getIndex(i); // 获取某个属性的Id值
if (itemId == R.styleable.EButtonComponent_ewidget_ebutton_backgroundDrawable) {// 设置按钮背景资源
Drawable drawable = ta.getDrawable(itemId);
this.setBackgroundDrawable(drawable);
}
}
}
}