编写可复用的自定义按钮
编写可复用的自定义按钮
现在有个正在开发的Android项目,里面已经有了一些不合理的UI实现方式。比如按钮是一张图:
可以看出,应该用编程的方式来实现这个按钮,比如xml声明drawable,一个矩形框,四个边是圆角,要有个很细的边框,黑色的,背景色使用渐进色效果。登录使用文字而不是在图形里。
这样的好处很多:
·自由的在不同分辨率屏幕下做适配,不必考虑图形的长宽比;
·当文字改动后,不必喊上美工一起加班处理;
·文字的国际化。
本文方案的基本思路是,还是用这个图,但是增加复用性,开发者只需在布局中使用自定义按钮,就可以让已经存在的这种布局具备点击后高亮的效果,而不必准备多张图,写冗长的xml文件做selector。
实现后的效果,在手指触碰到该按钮的时候:
抬起或者移动到按钮外区域恢复原来的样子。
这里布局还是在xml中,类似这样:
<com.witmob.CustomerButton
android:id=”@+id/login”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentLeft=”true”
android:layout_centerVertical=”true”
android:layout_marginLeft=”26dp”
android:background=”@drawable/login_login_but”/>
实现的按钮代码:
packagecom.witmob;
importandroid.content.Context;
importandroid.graphics.LightingColorFilter;
importandroid.graphics.Rect;
importandroid.util.AttributeSet;
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.widget.Button;
publicclassCustomerButtonextendsButton{
publicCustomerButton(Contextcontext){
super(context);
this.init();
}
publicCustomerButton(Contextcontext,AttributeSetattrs,intdefStyle){
super(context,attrs,defStyle);
this.init();
}
publicCustomerButton(Contextcontext,AttributeSetattrs){
super(context,attrs);
this.init();
}
privatevoidinit(){
this.setOnTouchListener(newOnTouchListener(){
@Override
publicbooleanonTouch(Viewv,MotionEventevent){
intaction=event.getActionMasked();
switch(action){
caseMotionEvent.ACTION_DOWN:
getBackground().setColorFilter(newLightingColorFilter(0xFFFFFFFF,0x000000FF));
getBackground().invalidateSelf();
break;
caseMotionEvent.ACTION_UP:
getBackground().clearColorFilter();
getBackground().invalidateSelf();
break;
caseMotionEvent.ACTION_MOVE:
Rectrect=newRect();
v.getDrawingRect(rect);
if(!rect.contains((int)event.getX(),(int)event.getY())){
getBackground().clearColorFilter();
getBackground().invalidateSelf();
}
break;
default:
break;
}
returnfalse;
}
});
}
}
代码要点:
·需要使用OnTouchListener,处理手指按下,抬起和移动到区域外的处理;
·使用ColorFilter,获取背景色的Drawable对象,增加颜色过滤;
·操作Rect,结合手指坐标,判断是否在区域内部;
·另外,需要返回false,在OnTouchListener,否则按钮的OnClickListener将不能生效。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。