本文共 3956 字,大约阅读时间需要 13 分钟。
@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); int width = getWidth(); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams(); layoutParams.width= (int) (width*0.5); layoutParams.height=(int) (width*0.5); layoutParams.topMargin=(int) (width*0.05); textView.setTextSize((float) (width*0.09));}
@Overridepublic boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN:; if(pressImage!=0){ imageView.setImageResource(pressImage); } break; case MotionEvent.ACTION_UP: textView.setTextColor(textcolorDefault); if(defaultImage!=0){ imageView.setImageResource(defaultImage); } break; } return true;}
//点击事件接口public interface MyStateButtonClickListener { void onClick(View view);} @Overridepublic boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN:; textView.setTextColor(textcolorPress); if(pressImage!=0){ imageView.setImageResource(pressImage); } break; case MotionEvent.ACTION_UP: textView.setTextColor(textcolorDefault); if(defaultImage!=0){ imageView.setImageResource(defaultImage); } //抬起时执行点击事件 if(myStateButtonClickListener!=null){ myStateButtonClickListener.onClick(view); } break; } return true;}
// 初始化GradientDrawable用于显示边框 defaultDrawable = new GradientDrawable(); pressDrawable = new GradientDrawable(); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyStateButton); if(typedArray!=null){// 默认图片 defaultImage = typedArray.getResourceId(R.styleable.MyStateButton_defaultImage, R.mipmap.one);// 点击图片 pressImage = typedArray.getResourceId(R.styleable.MyStateButton_pressImage, R.mipmap.one_press);// 设置文字 String text = typedArray.getString(R.styleable.MyStateButton_text);// 默认文字颜色 textcolorDefault = typedArray.getColor(R.styleable.MyStateButton_defaultTextColor, Color.parseColor("#567DBF"));// 点击文字颜色 textcolorPress = typedArray.getColor(R.styleable.MyStateButton_pressTextColor, Color.parseColor("#BFBFBF")); imageView.setImageResource(defaultImage); textView.setTextColor(textcolorDefault); textView.setText(text);// 默认边框颜色 borderColorDefault = typedArray.getColor(R.styleable.MyStateButton_defaultBorderColor, Color.parseColor("#567DBF"));// 点击边框颜色 borderColorPress = typedArray.getColor(R.styleable.MyStateButton_pressBorderColor, Color.parseColor("#BFBFBF"));// 边框宽度 borderWidth = typedArray.getInteger(R.styleable.MyStateButton_borderWidth, 2);// 边框圆角大小 cornerRadius = typedArray.getFloat(R.styleable.MyStateButton_cornerRadius, 8); defaultDrawable.setStroke(borderWidth,borderColorDefault); pressDrawable.setStroke(borderWidth,borderColorPress); defaultDrawable.setCornerRadius(cornerRadius); pressDrawable.setCornerRadius(cornerRadius); setBackground(defaultDrawable); }
转载地址:http://qityo.baihongyu.com/