1,需求背景;
按钮 按下时图片变大;松开时缩小; 这种情况很多时候我们在onTouch事件是来个控件的缩放动画就可以轻松实现;但是UI提出不能这样做,图片放大后效果不一样的;有特效;那就UI切二个大小相同的图片,我们直接替换就好了;可是UI发现图标都按照放大的切根本摆不下;最后就切了二个不通大小的图片;
如果,你直接替换图片的时候你会发现 放大的图片是被压缩的;
2,直接上代码; 懂得人自然秒懂;
public class MyZoomButton extends RelativeLayout {
String text ;
Drawable imgNormal ;
Drawable imgPressed ;
OnClickListener l ;
public void setOnClickListener( OnClickListener l){
this.l=l;
}
public MyZoomButton(Context context) {
this(context,null);
}
public MyZoomButton(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MyZoomButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
addUI(context);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.zoom_button);
text = typedArray.getString(R.styleable.zoom_button_text);
imgNormal = typedArray.getDrawable(R.styleable.zoom_button_imageview_normal_drawable);
imgPressed = typedArray.getDrawable(R.styleable.zoom_button_imageview_pressed_drawable);
if(text==null||imgNormal==null||imgPressed==null){
Log.e("ZoomButton","typedArray is have null !!!!");
}
typedArray.recycle();
}
private void addUI(Context context) {
final ImageView img = new ImageView(context);
img.setClickable(true);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(308,439);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
img.setLayoutParams(lp);
img.setImageDrawable(imgNormal);
addView(img);
final TextView textView = new TextView(context);
textView.setTextColor(Color.parseColor("#c0d8ff"));
textView.setTextSize(40);
textView.setGravity(Gravity.CENTER);
textView.setText(text);
final RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.topMargin=249;
lp2.rightMargin= 15;
textView.setLayoutParams(lp2);
addView(textView);
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(328,439);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
img.setLayoutParams(lp);
img.setImageDrawable(imgPressed);
lp2.rightMargin= 0;
textView.setLayoutParams(lp2);
textView.setTextSize(50);
}else if(motionEvent.getAction()==MotionEvent.ACTION_UP){
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(308,439);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
img.setLayoutParams(lp);
img.setImageDrawable(imgNormal);
lp2.rightMargin= 15;
textView.setLayoutParams(lp2);
textView.setTextSize(40);
}
return false;
}
});
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(l!=null){
view.setId(getId()); // 这里为什么传我的父类的id呢 就是因为我不希望父类被点击;当又要被看成父类被点击
l.onClick(view);
}
}
});
}
}