自定义组合控件的步骤基本大致有如下五个步骤,
首先,继承一个view Group,比如说是linearLayout,relayouy;
然后定义其的相关属性,获取其相关属性,比如说是颜色,大小等;
接着就是加载组合的view,根据属性修改UI/数据,比如面的按键变色;
第四步就是添加处理事件、数据,比如按钮的点击事件;
最后就是定义功能接口,对外暴露设置接口的方法,让外界可以唤醒其功能
下面做一个数字键盘为例,帮助理解自定义组合控件:
开始,定义一个view,继承自view Group,linearLayout:
public class LonginKeyboard extends LinearLayout {
public LonginKeyboard(Context context) {
this(context,null);
}
public LonginKeyboard(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public LonginKeyboard(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//
}
}
第二步,定义相关属性,获取相关属性:比如给颜色,大小,限制等等;
第三步,加载组合的view,根据属性修改UI/数据
比如我这里做一个数字键盘,那么它的布局为
因为相同因素过多,所以整合在styles.xml里,如下
- center
- @drawable/selector_num_key_pad
- #ffffff
- bold
- 18sp
- 4dp
- 1
- 0dp
- 50dp
定义点击提醒,分别在drawable包建立shape_num_key_pad_normal.xml、shape_num_key_pad_press.xml和selector_num_key_pad.xml。
shape_num_key_pad_normal.xml如下:
shape_num_key_pad_press.xml如下:
selector_num_key_pad.xml如下:
第四步,编写处理事件/数据
在java处增加点击事件:
private static final String TAG = "LonginKeyboard";
public LonginKeyboard(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public LonginKeyboard(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//
LayoutInflater.from(context).inflate(R.layout.num_key_pad,this);
initView();
}
private void initView() {
this.findViewById(R.id.number_1).setonClickListener(this);
this.findViewById(R.id.number_2).setonClickListener(this);
this.findViewById(R.id.number_3).setonClickListener(this);
this.findViewById(R.id.number_4).setonClickListener(this);
this.findViewById(R.id.number_5).setonClickListener(this);
this.findViewById(R.id.number_6).setonClickListener(this);
this.findViewById(R.id.number_7).setonClickListener(this);
this.findViewById(R.id.number_8).setonClickListener(this);
this.findViewById(R.id.number_9).setonClickListener(this);
this.findViewById(R.id.number_0).setonClickListener(this);
this.findViewById(R.id.back).setonClickListener(this);
}
@Override
public void onClick(View view) {
int viewId = view.getId();
if (mKeyPressListener == null){
Log.d(TAG,"mKeyPressListener is null need not call back ..");
return;
}
if (viewId == R.id.back){
//走back
mKeyPressListener.onBackPress();
}else {
//走数字结果通知
String text = ((TextView) view).getText().toString();
Log.d(TAG,"click text is ->"+text);
mKeyPressListener.onNumberPress(Integer.parseInt(text));
}
}
最后一步:定义功能接口,对外暴露设置接口方法
public void seronKeyPressListener(onKeyPressListener listener){
this.mKeyPressListener = listener;
}
public interface OnKeyPressListener{
void onNumberPress(int number);
void onBackPress();
}
结果如下:



