![](https://img.haomeiwen.com/i9134822/27f80301ecca4cb2.jpg)
TextView、Button 点击效果
-
设置点击和非点击两种状态特定颜色——用 shape、selector,当需要波纹效果可设置 foreground,当也需要底部点击阴影效果可设置 style。
01.gif
<TextView
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_marginTop="20dp"
android:textSize="16sp"
android:gravity="center"
android:text="效果"
android:textColor="@color/white"
android:foreground="?android:attr/selectableItemBackground"
android:background="@drawable/sel_text_bg"
style="@style/Widget.AppCompat.Button"/>
---------------------------------------------分隔线---------------------------------------------
// sel_text_bg.xml
<?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>
-
当有的要求更高,需要设置波纹效果的颜色——用 ripple 水波纹
02.gif
<Button
android:layout_width="200dp"
android:layout_height="60dp"
android:textSize="16sp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="效果"
android:textColor="@color/white"
android:background="@drawable/sel_text_ripple_bg"/>
---------------------------------------------分隔线---------------------------------------------
// sel_text_ripple_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<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>
ImageView 点击效果
/**
* Created on 2021/12/11 9:35
*
* @author Gong Youqiang
*/
public class ClickImageView extends AppCompatImageView {
public ClickImageView(@NonNull Context context) {
this(context,null);
}
public ClickImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@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);
}
}
网友评论