Android设置常见控件点击效果

一. Imageview的点击效果——图片稍微变暗突出点击效果

public class ClickImageView extends AppCompatImageView { public ClickImageView(Context context) { super(context); } public ClickImageView(Context context, AttributeSet attrs) { super(context, attrs); } public ClickImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: this.setColorFilter(0x99000000); return true; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: this.setColorFilter(null); break; } return super.onTouchEvent(event); } } 

二. Button、TextView的点击效果

  1. 仅仅突出点击效果(点击之后不需要特定颜色)——用style(不用shapeselector),当需要波纹效果可设置foreground
    <TextView
        android:layout_width="150dp"
        android:layout_height="wrap_content" android:text="点击效果" android:textColor="#DDFFFFFF" android:foreground="?android:attr/selectableItemBackground"//波纹效果 android:background="@drawable/shape_5dp_blue" style="@style/Widget.AppCompat.Button"/> //设置弧度、颜色(shape_5dp_blue) <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="5dp"/> <solid android:color="@android:color/holo_blue_dark"/> </shape> 
 
TextView的click.gif
  1. 设置点击和非点击两种状态特定颜色——用shapeselector,当需要波纹效果可设置foreground,当也需要底部点击阴影效果可设置style
<TextView
        android:layout_width="150dp"
        android:layout_height="wrap_content" android:text="点击效果" android:textColor="#DDFFFFFF" android:foreground="?android:attr/selectableItemBackground"//当需要波纹效果 android:background="@drawable/selector_5dp_blue" ![点击效果.gif](http://upload-images.jianshu.io/upload_images/3067748-e6e6601170e3b21a.gif?imageMogr2/auto-orient/strip) style="@style/Widget.AppCompat.Button" /> (selector_5dp_blue) <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape> <solid android:color="@android:color/holo_red_dark"/> <corners android:radius="5dp"/> </shape> </item> <item android:state_pressed="false"> <shape> <solid android:color="@android:color/holo_blue_dark"/> <corners android:radius="5dp"/> </shape> </item> </selector> 
 
点击效果.gif
  1. 当有的要求更高,需要设置波纹效果的颜色——用ripple(只能在21或以上使用,所以新建drawable-v21,都是命名selector_5dp_blue)
(selector_5dp_blue)
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@android:color/holo_red_dark"> <item> <selector> <item android:state_pressed="true"> <shape> <solid android:color="@android:color/holo_red_dark"/> <corners android:radius="5dp"/> </shape> </item> <item android:state_pressed="false"> <shape> <solid android:color="@android:color/holo_blue_dark"/> <corners android:radius="5dp"/> </shape> </item> </selector> </item> </ripple> 
 
点击效果.gif


作者:我想成为创业者
链接:https://www.jianshu.com/p/68fac9baf077
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自www.cnblogs.com/yelanggu/p/9933137.html