一. 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的點擊效果
- 僅僅突出點擊效果(點擊之后不需要特定顏色)——用
style
(不用shape
、selector
),當需要波紋效果可設置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
- 設置點擊和非點擊兩種狀態特定顏色——用
shape
、selector
,當需要波紋效果可設置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"  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
- 當有的要求更高,需要設置波紋效果的顏色——用
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
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。