1、Imageview代码实现按下效果,无需按下效果图片就可以实现。该怎么做呢?我们自定义个一个Imageview 继承ImageView。实现
onTouchEvent()方法,当按下的时候设置alpha( 一般建议0.5),当按下停止时,设置为原来的alpha(1.0)
public class PressImageView extends ImageView { public PressImageView(Context context) { super(context); } public PressImageView(Context context, AttributeSet attrs) { super(context, attrs); } public PressImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: setAlpha(0.5f); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_OUTSIDE: setAlpha(1.0f); break; } return super.onTouchEvent(event); } }
2、同样 TextView 是同样的原理,直接贴代码:当产品和ui设计师想让你按下的时候文字也有一个按下效果时,就可以派上用场了
public class PressTextView extends TextView { public PressTextView(Context context) { super(context); } public PressTextView(Context context, AttributeSet attrs) { super(context, attrs); } public PressTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: setAlpha(0.6f); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_OUTSIDE: setAlpha(1.0f); break; } return super.onTouchEvent(event); } }
2、使用起来也很简单:将这个类直接替换原先的TextView
<包名.xx.xx.PressTextView //这个类在你的项目中的实际路径
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:text="有按下效果的textview"
android:textColor="#fffabc"
android:textSize="16sp" />
使用这个按下效果的PressImageView ,用一张图片资源也可以轻松实现按下效果,不用ui给你切两张图,再写个selector了。
<包名.xx.xx.PressImageView //这个类在你的项目中的实际路径
android:id="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" />